Python脚本实现网卡流量监控
#/usr/bin/env/python
#coding=utf-8
importsys,re,time,os
maxdata=50000#单位KB
memfilename='/tmp/newnetcardtransdata.txt'
netcard='/proc/net/dev'
defcheckfile(filename):
ifos.path.isfile(filename):
pass
else:
f=open(filename,'w')
f.write('0')
f.close()
defget_net_data():
nc=netcardor'/proc/net/dev'
fd=open(nc,"r")
netcardstatus=False
forlineinfd.readlines():
ifline.find("eth0")>0:
netcardstatus=True
field=line.split()
recv=field[0].split(":")[1]
recv=recvorfield[1]
send=field[8]
ifnotnetcardstatus:
fd.close()
print'Pleasesetupyournetcard'
sys.exit()
fd.close()
return(float(recv),float(send))
defmonfirst(filename):
nowtime=time.strftime('%m-%d%H:%M',time.localtime(time.time()))
sec=time.localtime().tm_sec
ifnowtime=='01-0100:00':
ifsec<10:
f=open(filename,'w')
f.write('0')
f.close()
defnet_loop():
(recv,send)=get_net_data()
checkfile(memfilename)
monfirst(memfilename)
lasttransdaraopen=open(memfilename,'r')
lasttransdata=lasttransdaraopen.readline()
lasttransdaraopen.close()
totaltrans=int(lasttransdata)or0
whileTrue:
time.sleep(3)
(new_recv,new_send)=get_net_data()
recvdata=(new_recv-recv)/1024
senddata=(new_send-send)/1024
totaltrans+=int(recvdata)
totaltrans+=int(senddata)
memw=open(memfilename,'w')
memw.write(str(totaltrans))
memw.close()
iftotaltrans>=maxdata:
os.system('init0')
if__name__=="__main__":
net_loop()
用ROOT权限运行,maxdata为最大流量限制超过这个限制,系统自动关机当然,你可以改os.system('init0')为你想要的命令主要是现在VPS都限制流量,才搞了这个小脚本