項目背景:python
利用python實現一個自動化的網卡流量圖表繪製,這對於咱們實現自動化運維平臺有更深刻的理解,數據庫
也會讓咱們對於現有的一些監控軟件的一些實現都有很大的幫助。centos
實現環境:服務器
虛擬機VMware Workstation 12 player運維
服務器:centos6.5的系統 ip:192.168.0.25ssh
python2.6.6ide
rrdtool模塊、time模塊、psutil模塊。學習
SecureCRT ssh遠程鏈接軟件
url
實驗過程:spa
思路其實很清醒:建立rrd數據庫---->數據寫入rrd數據庫----->根據數據畫圖 ok!!!完事兒
1、首先建立咱們的工做目錄,而後建立三個文件(create.py、update.py、graph.py)。
2、建立rrd數據庫。
[root@ www rrdtool]# cat create.py
#!/usr/bin/env python
import rrdtool
import time
cur_time=str(int(time.time()))
rrd=rrdtool.create('Flow.rrd','--step','300','--start',cur_time,
'DS:eth0_in:COUNTER:600:0:U',
'DS:eth0_out:COUNTER:600:0:U',
'RRA:AVERAGE:0.5:1:600',
'RRA:AVERAGE:0.5:6:700',
'RRA:AVERAGE:0.5:24:775',
'RRA:AVERAGE:0.5:288:797',
'RRA:MAX:0.5:1:600',
'RRA:MAX:0.5:6:700',
'RRA:MAX:0.5:24:775',
'RRA:MAX:0.5:444:797',
'RRA:MIN:0.5:1:600',
'RRA:MIN:0.5:6:700',
'RRA:MIN:0.5:24:775',
'RRA:MIN:0.5:444:797')
if rrd:
print rrdtool.error()
賦予執行權限執行一下。
3、數據寫入到rrd數據庫
[root@ www rrdtool]# cat update.py
#!/usr/bin/env python
import rrdtool
import time,psutil
total_input_traffic = psutil.net_io_counters()[1]
total_output_traffic = psutil.net_io_counters()[0]
starttime=int(time.time())
update=rrdtool.updatev('/home/test/rrdtool/Flow.rrd','%s:%s:%s' %
(str(starttime),str(total_input_traffic),str(total_output_traffic)))
print update
執行一下,數據寫入~~~
[root@ www rrdtool]# cat graph.py
#!/usr/bin/python
import rrdtool
import time
title="Server network traffic flow ("+time.strftime('%Y-%m-%d',
time.localtime(time.time()))+")"
rrdtool.graph( "Flow.png", "--start", "-1d","--vertical-label=Bytes/s",
"--x-grid","MINUTE:12:HOUR:1:HOUR:1:0:%H",
"--width","650","--height","230","--title",title,
"DEF:inoctets=Flow.rrd:eth0_in:AVERAGE",
"DEF:outoctets=Flow.rrd:eth0_out:AVERAGE",
"CDEF:total=inoctets,outoctets,+",
"LINE1:total#FF8833:Total traffic",
"AREA:inoctets#00FF00:In traffic",
"LINE1:outoctets#0000FF:Out traffic",
"HRULE:6144#FF0000:Alarm value\\r",
"CDEF:inbits=inoctets,8,*",
"CDEF:outbits=outoctets,8,*",
"COMMENT:\\r",
"COMMENT:\\r",
"GPRINT:inbits:AVERAGE:Avg In traffic\: %6.2lf %Sbps",
"COMMENT: ",
"GPRINT:inbits:MAX:Max In traffic\: %6.2lf %Sbps",
"COMMENT: ",
"GPRINT:inbits:MIN:MIN In traffic\: %6.2lf %Sbps\\r",
"COMMENT: ",
"GPRINT:outbits:AVERAGE:Avg Out traffic\: %6.2lf %Sbps",
"COMMENT: ",
"GPRINT:outbits:MAX:Max Out traffic\: %6.2lf %Sbps",
"COMMENT: ",
"GPRINT:outbits:MIN:MIN Out traffic\: %6.2lf %Sbps\\r")
執行它,繪圖!!!
能夠看到咱們生成了一個圖片,你確定是想看一幅漂亮的圖片,而不是這個!!!!
能夠看到,有沒有很神奇!!!!!!!!!!!!件至關於咱們本身寫了一個監控軟件,並且看起來還很美!!!!!
總結:經過這個項目咱們能夠對與監控有更清晰的認識,其實通常也就這三步:
建立rrd數據庫---->數據寫入rrd數據庫----->根據數據畫圖 ok!!!完事兒
但願你們能夠獲得學習,謝謝,知識在於共享!!!!