python版监控linux流量
直接上代码,使用OptionParser来传入参数
#coding:utf-8#-------------#Author:Hu#Data:20150520#-------------from__future__importdivisionimportreimporttimefromoptparseimportOptionParserdefgetbandwidth(eth='eth0',intevel=1):
a=open('/PRoc/net/dev')
data=a.read()
patten=eth +'.*'ifnotre.search(patten,data):print"The ETHname not have"exit(1)
Rev_old=re.search(patten,data).group().replace(':','').split()[1]
Send_old=re.search(patten,data).group().replace(':','').split()[9]
a.close()whileTrue:#print inteveltime.sleep(int(intevel))
a=open('
/proc/net/dev')
data=a.read()
Rev=re.search(patten,data).group().replace(':','').split()[1]
Send=re.search(patten,data).group().replace(':','').split()[9]
diff_Rev=int(Rev)-int(Rev_old)
diff_Sen=int(Send)-int(Send_old)
diff_M=diff_Rev*8/1024/1024/int(intevel)
diff_S=diff_Sen*8/1024/1024/int(intevel)printtime.strftime("%Y%m%d %H:%M:%S") +'The Recevie is %6.2f Mbps(byte is %d)'% (diff_M,diff_Rev) +'The Send is %6.2f Mbps(byte is %d)'%(diff_S,diff_Sen)
Rev_old=Rev
Send_old=Send
a.close()if__name__=='__main__':importsys
usage='''%prog [-i ethname] [-t interveltime]
Example:%prog -i eth0 -t 1'''parser=OptionParser(usage=usage,version='2.0_20150602')
parser.add_option('-i','--interface',dest='interface',default='eth0',help='Wann to interface')
parser.add_option('-t','--time',dest='intevel',type='int',default='1',help='The intevel time')
(options,args)=parser.parse_args()print"The interafce is %s and the intevel time is %d"%(options.interface,options.intevel)
getbandwidth(options.interface,options.intevel)
使用方法:
'''%prog [-i ethname] [-t interveltime]
Example:%prog -i eth0 -t 1'''
默认是eth0 ,时间间隔是1
效果如下:
[root@iZ94nv1rj5tZ tools]# ./bandwidth3.py -version
Usage: bandwidth3.py [-i ethname] [-t interveltime]
Example:bandwidth3.py-i eth0 -t1bandwidth3.py: error: no such option:-v
[root@iZ94nv1rj5tZ tools]# ./bandwidth3.py -i eth1 -t1The interafce is eth1 and the inteveltimeis12015111316:51:43The Recevie is0.01Mbps(byteis1876) The Send is0.00Mbps(byteis154)2015111316:51:44The Recevie is0.02Mbps(byteis2156) The Send is0.00Mbps(byteis202)2015111316:51:45The Recevie is0.08Mbps(byteis10482) The Send is0.00Mbps(byteis202)2015111316:51:46The Recevie is0.02Mbps(byteis2014) The Send is0.00Mbps(byteis202)2015111316:51:47The Recevie is0.02Mbps(byteis2612) The Send is0.00Mbps(byteis202)2015111316:51:48The Recevie is0.09Mbps(byteis11394) The Send is0.00Mbps(byteis202)
如有问题,请联系362299908@QQ.com