-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnethogs.py
138 lines (111 loc) · 3.94 KB
/
nethogs.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
"""nethogs.py: from https://github.com/akshayKMR/hogwatch/blob/master/hogwatch/server/watchdogs/nethogs.py."""
import subprocess, sys
try:
from queue import Queue
except:
from Queue import Queue#py2
from pprint import pprint
from decimal import Decimal
import time
import atexit
class NethogsWatchdog:
def __init__(self, debug=False, devices=[], delay=1):
from sys import platform as _platform
if _platform == "linux" or _platform == "linux2":
pass
# linux
elif _platform == "darwin":
if len(devices) == 0:
# devices=['en0']
pass
elif _platform == "win32":
print
"Windows is not supported."
self.devices = devices
self.delay = str(delay)
self.debug = debug
self._running = True
def terminate(self):
self._running = False
def watch_transfer(self, mode='transfer_rate', bridge={}):
# param 0=rate, 3 amount in MB
if mode not in ['transfer_rate', 'transfer_amount']:
raise ValueError('mode not supported')
if mode == 'transfer_rate':
param = '0'
else:
param = '1'
cmd = ['nethogs', '-d', self.delay, '-v', param, '-t'] + self.devices
if self.debug:
print
cmd
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
atexit.register(p.terminate)
# need json output :/
refresh_flag = True
report = {}
report['mode'] = mode
report['running'] = True
report['ctr'] = 0
entries = []
for line in iter(p.stdout.readline, b''):
if (self._running == False):
break
print(line)
# print line
if (line.find(b'Refreshing') == -1):
if refresh_flag:
continue
split = line.split()
if (len(split) != 3):
continue
entry = {}
pline = split[0].decode()
psplit = pline.split('/')
entry['process'] = pline
entry['path'] = "/".join(psplit[:-2])
entry['pid'] = psplit[-2]
entry['filename'] = psplit[-3]
if (mode == 'transfer_rate'):
entry['kbps_out'] = float(split[1])
entry['kbps_in'] = float(split[2])
else: # mode is 'transfer_amount'
entry['kb_out'] = float(split[1])
entry['kb_in'] = float(split[2])
entries.append(entry)
else:
if refresh_flag:
refresh_flag = False
continue
if (len(entries) == 0):
continue
total_in, total_out = 0, 0
for entry in entries:
if (report['mode'] == 'transfer_rate'):
total_in += entry['kbps_in']
total_out += entry['kbps_out']
else:
total_in += entry['kb_in']
total_out += entry['kb_out']
report['total_in'] = total_in
report['total_out'] = total_out
report['entries'] = entries
report['ctr'] += 1
entries = []
if self.debug:
print(line)
pprint(report)
else:
report['timestamp'] = int(round(time.time() * 1000)) # js time format
bridge['queue'].put(report)
p.terminate()
if self.debug:
print
'exited nethogs'
else:
report = {}
report['running'] = False
bridge['queue'].put(report)
if __name__ == '__main__':
x = NethogsWatchdog(debug=True, devices=sys.argv[1:])
x.watch_transfer()