linux系统下用python脚本监控网卡流量

linux系统下用python脚本监控网卡流量

大部份的VPS都是有流量限制的,达到一定的流量,要么强制停了你的机器,要么付钱给超了的流量。因为有台VPS是绑了信用卡的,担心流量超了会被扣钱,所以就想在服务器上跑个程序,实时的监控网卡的流量,若达到了一定的值就停了web服务,防止流量超了被扣钱。

Google了一下,网上已经有很多现成的脚本程序了,找了个是用python写的,在服务器上测试了一下能用,特记录下来:

cat /usr/sbin/moneth0.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/python
#coding=utf-8
import sys,re,time,os
maxdata = 320 #KB为单位
memfilename = '/tmp/servicelabs.com.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('service nginx stop')
 
if __name__ == "__main__":
net_loop()

新建一个文件,如/usr/sbin/moneth0.py文件,写入以上代码并给执行权限,然后以超级用户权限运行,其中参数maxdata为最大流量限制,超过这个限制,自动停nginx服务, 如果想执行其它命令,只需修改os.system(‘service nginx stop’)为你想要的命令即可!