现在主流监控软件和云平台提供的流量监控,监控粒度最小只能设置为1分钟,无法准备于定位故障,特别是瞬时突发较大的业务
对比python的snmp库还是更喜欢用subprocess调用snmpwalk命令,脚本如下,前端可以使用脚本采集到的数据进行绘图
#! /usr/bin/env python #coding = utf-8 import time,subprocess,re,signal,os class traffic: def __init__(self,ip,portMIB,community,interval): self.cmd_in=‘snmpwalk -v 2c -c %s %s ifHCInOctets.%s‘%(community,ip,portMIB) self.cmd_out=‘snmpwalk -v 2c -c %s %s ifHCOutOctets.%s‘%(community,ip,portMIB) self.interval = interval def form(self,data): ret = re.findall(‘Counter64:.*‘,data.decode(‘utf8‘))[0] ret = ret.split(‘:‘)[1].strip() ret = round(int(ret)*8/1024/1024,2) return ret def snmp(self): traffic_in = subprocess.Popen(self.cmd_in,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0] traffic_out = subprocess.Popen(self.cmd_out,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0] traffic_in = self.form(traffic_in) traffic_out = self.form(traffic_out) return(traffic_in,traffic_out) def gettraffic(self): befo_in,befo_out = self.snmp() time.sleep(self.interval) back_in,back_out = self.snmp() return ({‘in‘:round((back_in-befo_in)/5,2),‘out‘:round((back_out-befo_out)/5,2)}) if __name__ == "__main__": def signal_handler(*args, **kwargs): try: print(‘----------------------------end-----------------------------‘) print(‘traffic_in_min:%sMbps‘%traffic_in_min,‘traffic_in_max:%sMbps‘%traffic_in_max) print(‘traffic_in_avg:%sMbps‘%(round(traffic_in_sum/count,2)),‘traffic_in_avg:%sMbps‘%(round(traffic_out_sum/count,2))) print(‘traffic_out_min:%sMbps‘%traffic_out_min,‘traffic_out_max:%sMbps‘%traffic_out_max) except: os._exit(0) os._exit(0) signal.signal(signal.SIGINT, signal_handler) traffic_in_max = 0 traffic_out_max = 0 traffic_in_min = 999999999999 traffic_out_min = 999999999999 traffic_in_sum = 0 traffic_out_sum = 0 count = 0 host =‘10.0.0.1‘ portMIB = 559 community = ‘test‘ interval = 5 mx =traffic(host,portMIB,community,interval) print(‘-------------%s 5秒粒度流量监控------------------‘%host) while True: ret = mx.gettraffic() traffic_in = ret[‘in‘] traffic_out = ret[‘out‘] traffic_in_max = max(traffic_in,traffic_in_max) traffic_out_max = max(traffic_out,traffic_out_max) traffic_in_min = min(traffic_in,traffic_in_min) traffic_out_min = min(traffic_out,traffic_out_min) traffic_in_sum += traffic_in traffic_out_sum += traffic_out count+=1 print(‘traffic_in: %s Mbps‘%traffic_in,‘traffic_out: %s Mbps‘%traffic_out)