#创建rrd数据库 import rrdtool import time

cur_time=str(int(time.time())) rrd=rrdtool.create('Flow.rrd','--step','300','--start',cur_time, #Flow.rrd 文件名,--step表示写数据的频率,--start表示第一条记录的起始时间 'DS:eth0_in:COUNTER:600:0:U', #DS定义数据源,网卡eth0入流量,counter表示递增(DST定义数据类型),后面的表示600秒表示心跳值,满600秒没有收到数据,会用unknown代替,0为最小值,U为最大值 'DS:eth0_out:COUNTER:600:0:U', #DST有的类型:DERIVE(可增可减),ABSOLUTE(假定前一个的时间间隔为0,再计算平均值),GUAGE(收到值后直接存入RRA),COMPUTE(定义表达式,引用DS并自动计算出某个值) 'RRA:AVERAGE:0.5:1:600', #RRA定义数据存储格式 'RRA:AVERAGE:0.5:6:700', #CF统计合并数据,方式有AVERAGE、max、min,last最新值 'RRA:AVERAGE:0.5:24:775', #数字0.5表示一个CDP中的PDP值如果超过一半为UNKNOWN就被标为UNKNOWN, 'RRA:AVERAGE:0.5:288:797', #存储时间计算为0.5后的值乘以300秒,最后的值表示存值的次数 '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()) #============================================= #更新rrd数据库

!/usr/bin/python3

-- coding:utf-8 --

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('/root/python/Flow.rrd', '%s:%s:%s' % (str(starttime), str(total_input_traffic), str(total_output_traffic))) print(update['return_value']) #如果结果返回0为正常

#============================================================ #绘制图片 #!/usr/bin/python3

-- coding: utf-8 --

import rrdtool import time

#定义图表标题 title="Server network traffic flow ("+time.strftime('%Y-%m-%d',time.localtime(time.time()))+")" #--vertical-label指定y轴名称 #--x-grid设置x轴的时间间隔,MINUTE:12表示每隔12分钟放置一根次要格线,HOUR:1表示每隔1小时放置一根主要格线,、

第二个HOUR:1表示1个小时输出一个label标签,0表示数字对齐格线,%H表示标签以小时显示

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", #指定网卡入流量数据源DS和CF "DEF:outoctets=Flow.rrd:eth0_out:AVERAGE",##指定网卡出流量数据源DS和CF "CDEF:total=inoctets,outoctets,+", #通过CDEF合并出入流量统计总的流量 "LINE1:total#FF8833:Total traffic",#以线条的方式绘制总流量 "AREA:inoctets#00FF00:In traffic", #以面积方式绘制入流量 "LINE1:outoctets#0000FF:Out traffic", "HRULE:6144#FF0000:Alarm value\r",#绘制水平线作为警告线,阈值为6144 "CDEF:inbits=inoctets,8,",#将入流量换算成bit "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文件的结构信息 rrdtool info file_name.rrd #查看rrd文件第一个数据的更新时间 rrdtool first file_name.rrd #查看rrd文件最后一次更新的时间 rrdtool last file_name.rrd #使用fetch根据开始和结束时间,以及CF状态查询 rrdtool fetch file_name.rrd AVERAGE