psutil

Форк
0
/
nettop.py 
163 строки · 4.3 Кб
1
#!/usr/bin/env python3
2
#
3
# $Id: iotop.py 1160 2011-10-14 18:50:36Z g.rodola@gmail.com $
4
#
5
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
6
# Use of this source code is governed by a BSD-style license that can be
7
# found in the LICENSE file.
8

9
"""Shows real-time network statistics.
10

11
Author: Giampaolo Rodola' <g.rodola@gmail.com>
12

13
$ python3 scripts/nettop.py
14
-----------------------------------------------------------
15
total bytes:           sent: 1.49 G       received: 4.82 G
16
total packets:         sent: 7338724      received: 8082712
17

18
wlan0                     TOTAL         PER-SEC
19
-----------------------------------------------------------
20
bytes-sent               1.29 G        0.00 B/s
21
bytes-recv               3.48 G        0.00 B/s
22
pkts-sent               7221782               0
23
pkts-recv               6753724               0
24

25
eth1                      TOTAL         PER-SEC
26
-----------------------------------------------------------
27
bytes-sent             131.77 M        0.00 B/s
28
bytes-recv               1.28 G        0.00 B/s
29
pkts-sent                     0               0
30
pkts-recv               1214470               0
31
"""
32

33
import sys
34
import time
35

36

37
try:
38
    import curses
39
except ImportError:
40
    sys.exit('platform not supported')
41

42
import psutil
43
from psutil._common import bytes2human
44

45

46
lineno = 0
47
win = curses.initscr()
48

49

50
def printl(line, highlight=False):
51
    """A thin wrapper around curses's addstr()."""
52
    global lineno
53
    try:
54
        if highlight:
55
            line += " " * (win.getmaxyx()[1] - len(line))
56
            win.addstr(lineno, 0, line, curses.A_REVERSE)
57
        else:
58
            win.addstr(lineno, 0, line, 0)
59
    except curses.error:
60
        lineno = 0
61
        win.refresh()
62
        raise
63
    else:
64
        lineno += 1
65

66

67
def poll(interval):
68
    """Retrieve raw stats within an interval window."""
69
    tot_before = psutil.net_io_counters()
70
    pnic_before = psutil.net_io_counters(pernic=True)
71
    # sleep some time
72
    time.sleep(interval)
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)
76

77

78
def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
79
    """Print stats on screen."""
80
    global lineno
81

82
    # totals
83
    printl(
84
        "total bytes:           sent: %-10s   received: %s"
85
        % (
86
            bytes2human(tot_after.bytes_sent),
87
            bytes2human(tot_after.bytes_recv),
88
        )
89
    )
90

91
    # per-network interface details: let's sort network interfaces so
92
    # that the ones which generated more traffic are shown first
93
    printl("")
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"
100
        # fmt: off
101
        printl(templ % (name, "TOTAL", "PER-SEC"), highlight=True)
102
        printl(templ % (
103
            "bytes-sent",
104
            bytes2human(stats_after.bytes_sent),
105
            bytes2human(
106
                stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
107
        ))
108
        printl(templ % (
109
            "bytes-recv",
110
            bytes2human(stats_after.bytes_recv),
111
            bytes2human(
112
                stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
113
        ))
114
        printl(templ % (
115
            "pkts-sent",
116
            stats_after.packets_sent,
117
            stats_after.packets_sent - stats_before.packets_sent,
118
        ))
119
        printl(templ % (
120
            "pkts-recv",
121
            stats_after.packets_recv,
122
            stats_after.packets_recv - stats_before.packets_recv,
123
        ))
124
        printl("")
125
        # fmt: on
126
    win.refresh()
127
    lineno = 0
128

129

130
def setup():
131
    curses.start_color()
132
    curses.use_default_colors()
133
    for i in range(curses.COLORS):
134
        curses.init_pair(i + 1, i, -1)
135
    curses.endwin()
136
    win.nodelay(1)
137

138

139
def tear_down():
140
    win.keypad(0)
141
    curses.nocbreak()
142
    curses.echo()
143
    curses.endwin()
144

145

146
def main():
147
    setup()
148
    try:
149
        interval = 0
150
        while True:
151
            if win.getch() == ord('q'):
152
                break
153
            args = poll(interval)
154
            refresh_window(*args)
155
            interval = 0.5
156
    except (KeyboardInterrupt, SystemExit):
157
        pass
158
    finally:
159
        tear_down()
160

161

162
if __name__ == '__main__':
163
    main()
164

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.