python3实现
python3学习中写的一个小程序,有时候还挺有用,贴出来做记录!
依赖系统的net-tools工具,也就是ifconfig命令。
实现原理利用ifconfig查看网卡发送和接受的数据多少,利用re匹配出需要的数据,利用time模块计时算出
1s内发送或者接收数据的多少!
Note 依赖系统的net-tools工具,也就是ifconfig命令。1
sudo apt-get install net-tools
python3代码: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#!/usr/bin/env python3
import subprocess
import re
import time
def get_total(xdata):
s = set([(e[0],e[2]) for e in xdata])
d = dict(s)
d.pop('lo')
l=list(d.values())
li = [int(i) for i in l]
return sum(li)
def show(delta):
if delta < 1024:
n = int(delta)
s = 'B'
elif delta < 1024*1024:
n = delta//1024
s = 'KB'
else:
n = round(delta/(1024*1024),1)
s = 'MB'
return str(n)+s+'/S'
if __name__ == '__main__':
cmd = ['ifconfig']
rx_pat = re.compile(r'\b(\w+)\b:(.+\s+)+?RX.+?bytes\s+(\d+)')
tx_pat = re.compile(r'\b(\w+)\b:(.+\s+)+?TX.+?bytes\s+(\d+)')
try:
while True:
out_bytes = subprocess.check_output(cmd)
out_str = out_bytes.decode('utf-8')
rx = rx_pat.findall(out_str)
tx = tx_pat.findall(out_str)
rx_data1 = get_total(rx)
tx_data1 = get_total(tx)
time.sleep(1)
out_bytes = subprocess.check_output(cmd)
out_str = out_bytes.decode('utf-8')
rx = rx_pat.findall(out_str)
tx = tx_pat.findall(out_str)
rx_data2 = get_total(rx)
tx_data2 = get_total(tx)
subprocess.call("clear")
print("↑:"+show(tx_data2-tx_data1))
print("↓:"+show(rx_data2-rx_data1))
except subprocess.CalledProcessError as e:
out_bytes = e.output # Output generated before error
code = e.returncode # Return code
其他软件包实现–iftop
1 | sudo apt-get update |