9
"""Shows real-time network statistics.
11
Author: Giampaolo Rodola' <g.rodola@gmail.com>
13
$ python3 scripts/nettop.py
14
-----------------------------------------------------------
15
total bytes: sent: 1.49 G received: 4.82 G
16
total packets: sent: 7338724 received: 8082712
19
-----------------------------------------------------------
20
bytes-sent 1.29 G 0.00 B/s
21
bytes-recv 3.48 G 0.00 B/s
26
-----------------------------------------------------------
27
bytes-sent 131.77 M 0.00 B/s
28
bytes-recv 1.28 G 0.00 B/s
40
sys.exit('platform not supported')
43
from psutil._common import bytes2human
50
def printl(line, highlight=False):
51
"""A thin wrapper around curses's addstr()."""
55
line += " " * (win.getmaxyx()[1] - len(line))
56
win.addstr(lineno, 0, line, curses.A_REVERSE)
58
win.addstr(lineno, 0, line, 0)
68
"""Retrieve raw stats within an interval window."""
69
tot_before = psutil.net_io_counters()
70
pnic_before = psutil.net_io_counters(pernic=True)
73
tot_after = psutil.net_io_counters()
74
pnic_after = psutil.net_io_counters(pernic=True)
75
return (tot_before, tot_after, pnic_before, pnic_after)
78
def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
79
"""Print stats on screen."""
84
"total bytes: sent: %-10s received: %s"
86
bytes2human(tot_after.bytes_sent),
87
bytes2human(tot_after.bytes_recv),
94
nic_names = list(pnic_after.keys())
95
nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
96
for name in nic_names:
97
stats_before = pnic_before[name]
98
stats_after = pnic_after[name]
99
templ = "%-15s %15s %15s"
101
printl(templ % (name, "TOTAL", "PER-SEC"), highlight=True)
104
bytes2human(stats_after.bytes_sent),
106
stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
110
bytes2human(stats_after.bytes_recv),
112
stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
116
stats_after.packets_sent,
117
stats_after.packets_sent - stats_before.packets_sent,
121
stats_after.packets_recv,
122
stats_after.packets_recv - stats_before.packets_recv,
132
curses.use_default_colors()
133
for i in range(curses.COLORS):
134
curses.init_pair(i + 1, i, -1)
151
if win.getch() == ord('q'):
153
args = poll(interval)
154
refresh_window(*args)
156
except (KeyboardInterrupt, SystemExit):
162
if __name__ == '__main__':