发布于 2015-02-24 04:52:53 | 226 次阅读 | 评论: 0 | 来源: 网友投递
Python编程语言
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
这篇文章主要介绍了Python脚本实现网卡流量监控,本文直接给出实现代码,需要的朋友可以参考下
#/usr/bin/env/python
#coding=utf-8
import sys,re,time,os
maxdata = 50000 #单位KB
memfilename = '/tmp/newnetcardtransdata.txt'
netcard = '/proc/net/dev'
def checkfile(filename):
if os.path.isfile(filename):
pass
else:
f = open(filename, 'w')
f.write('0')
f.close()
def get_net_data():
nc = netcard or '/proc/net/dev'
fd = open(nc, "r")
netcardstatus = False
for line in fd.readlines():
if line.find("eth0") > 0:
netcardstatus = True
field = line.split()
recv = field[0].split(":")[1]
recv = recv or field[1]
send = field[8]
if not netcardstatus:
fd.close()
print 'Please setup your netcard'
sys.exit()
fd.close()
return (float(recv), float(send))
def monfirst(filename):
nowtime = time.strftime('%m-%d %H:%M',time.localtime(time.time()))
sec = time.localtime().tm_sec
if nowtime == '01-01 00:00':
if sec < 10:
f = open(filename, 'w')
f.write('0')
f.close()
def net_loop():
(recv, send) = get_net_data()
checkfile(memfilename)
monfirst(memfilename)
lasttransdaraopen = open(memfilename,'r')
lasttransdata = lasttransdaraopen.readline()
lasttransdaraopen.close()
totaltrans = int(lasttransdata) or 0
while True:
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()
if totaltrans >= maxdata:
os.system('init 0')
if __name__ == "__main__":
net_loop()
用ROOT权限运行,maxdata为最大流量限制 超过这个限制,系统自动关机 当然,你可以改os.system('init 0')为你想要的命令 主要是现在VPS都限制流量,才搞了这个小脚本