-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouteros_bw.py
87 lines (68 loc) · 2.03 KB
/
routeros_bw.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
#!/usr/bin/env python3
"""
Real-time per-ip bandwidth monitor for RouterOS. The absolute
bits-per-second values are not very accurate but they are useful
relatively.
./routeros_bw.py <router_ip>
See https://wiki.mikrotik.com/wiki/Manual:IP/Accounting for how to
configure IP Accounting *AND* web access.
"""
import time
import curses
import ipaddress
import socket
import sys
import urllib.request
from collections import defaultdict
ROUTER_HOSTNAME = sys.argv[1]
def get_stats():
url = "http://%s/accounting/ip.cgi" % ROUTER_HOSTNAME
with urllib.request.urlopen(url) as response:
data = response.read().decode('utf-8')
data = data.splitlines()
data = [l.split() for l in data if l]
# just [src, dst, bytes]
data = [l[:2] + [float(l[2])] for l in data]
# sum bytes by ip
rv = defaultdict(int)
for src, dst, bytes in data:
rv[src] += bytes
rv[dst] += bytes
rv = {ip: bytes for ip, bytes in rv.items()
if ipaddress.ip_address(ip).is_private}
return dict(rv)
def main(print_fn, cb_end=None):
hist = defaultdict(list) # bits keyed by ip
n = 0
window = 3
def output():
for ip in sorted(hist, key=lambda x: socket.inet_aton(x)):
h = hist[ip]
if sum(h) and len(h):
avg_bps = sum(h) / len(h)
else:
avg_bps = 0
print_fn("%s: %.0f kbps\n" % (ip, avg_bps / 1024))
while True:
n += 1
data = get_stats()
for ip, bits in data.items():
hist[ip].append(bits)
if n > window:
hist[ip] = hist[ip][-window:]
if n > window:
n = 0
output()
if cb_end:
cb_end()
time.sleep(1)
def main_window(stdscr):
def cb():
stdscr.clear()
def print_fn(s):
stdscr.addstr(s)
stdscr.refresh()
main(print_fn=print_fn, cb_end=cb)
stdscr.refresh()
stdscr.getkey()
curses.wrapper(main_window)