我是靠谱客的博主 搞怪乌龟,这篇文章主要介绍Python脚本实现网卡流量监控,现在分享给大家,希望可以做个参考。

复制代码
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
66
#/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都限制流量,才搞了这个小脚本

最后

以上就是搞怪乌龟最近收集整理的关于Python脚本实现网卡流量监控的全部内容,更多相关Python脚本实现网卡流量监控内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(258)

评论列表共有 0 条评论

立即
投稿
返回
顶部