释放双眼,带上耳机,听听看~!
简介
利用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 1#/usr/bin/env/python
2#coding=utf-8
3import sys,re,time,os
4import json
5import requests
6
7url = ''
8
9netcard = '/proc/net/dev'
10def get_net_data():
11 nc = netcard or '/proc/net/dev'
12 fd = open(nc, "r")
13 netcardstatus = False
14 for line in fd.readlines():
15 if line.find("eth0") >= 0 or line.find("enp") >= 0:
16 netcardstatus = True
17 field = line.split()
18 recv = field[0].split(":")[1]
19 recv = recv or field[1]
20 send = field[8]
21 if not netcardstatus:
22 fd.close()
23 print 'Please setup your netcard'
24 sys.exit()
25 fd.close()
26 return (float(recv), float(send))
27
28def send_warn(recv_data, send_data):
29 content = "亚马逊服务器一分钟流量警告,recv_data: %s kb, send_data: %s kb"%(recv_data, send_data)
30 text = {
31 "msgtype": "text",
32 "text": {
33 "content": content
34 },
35 "at": {
36 "atMobiles": [
37 "156xxxx8827",
38 "189xxxx8325"
39 ],
40 "isAtAll": False
41 }
42 }
43 headers = {'content-type': 'application/json'}
44
45 r = requests.post(url, data=json.dumps(text), headers=headers)
46 print r.text
47
48def net_loop():
49 recv,send = get_net_data()
50 while True:
51 time.sleep(60)
52 new_recv,new_send = get_net_data()
53 recv_data = (new_recv - recv)/1024
54 send_data = (new_send - send)/1024
55 print "recv_data: %s kb, send_data: %s kb"%(recv_data, send_data)
56 if recv_data/60>100 or send_data/60>10:
57 send_warn(recv_data, send_data)
58 recv,send = new_recv,new_send
59
60if __name__ == "__main__":
61 net_loop()
62
63