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
67
68
69
70
import time
import threading
import signal
from datetime import datetime
last_in_bytes = None
last_out_bytes = None
def (inf):
global last_in_bytes, last_out_bytes
in_traffic, out_traffic = None, None
with open('/proc/net/dev') as f:
lines = f.readlines()
for line in lines[2:]:
line = line.strip()
if line.startswith(inf + ':'):
items = line.strip().split(':')[1].split()
in_bytes, out_bytes = int(items[0]), int(items[8])
if last_in_bytes:
in_traffic, out_traffic = in_bytes - last_in_bytes, out_bytes - last_out_bytes
last_in_bytes, last_out_bytes = in_bytes, out_bytes
return in_traffic, out_traffic
next_thread = None
exit_flag = False
def thread_job(f_handler, inf='eth0', interval=2):
global next_thread, exit_flag
time.sleep(interval)
if not exit_flag:
next_thread = threading.Thread(target=thread_job, args=(f_handler, inf, interval))
next_thread.start()
else:
next_thread = None
time_stamp = int(time.time())
in_traffic, out_traffic = curr_traffic(inf)
print in_traffic, out_traffic
if in_traffic is not None and out_traffic is not None and not f_handler.closed:
f_handler.write('%d, %d, %dn' % (time_stamp, in_traffic, out_traffic))
def exit_func(signum, stack):
global exit_flag
exit_flag = True
print("Exiting ...")
cnt = 0
while not next_thread and cnt < 3:
time.sleep(1)
cnt += 1
if cnt >= 3:
next_thread.exit()
def output_traffics(outfile, inf='eth0', interval=1):
with open(outfile, 'w') as f:
f.write('time, in_rate(B/s), out_rate(B/s)n')
thread_job(f, inf, interval)
while not exit_flag:
time.sleep(1)
if __name__ == '__main__':
signal.signal(signal.SIGINT, exit_func)
signal.signal(signal.SIGINT, exit_func)
args = {
'outfile': time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) + '.csv',
'inf': 'eth0',
'interval': 1
}
output_traffics(**args)