我正在尝试通过 python 代码计算 wlan1
接口(interface)上的总网络流量。到目前为止,我尝试了 ethtool
、iftop
、ifstat
、nethogs
但大多数这些工具都显示 ncurses 界面(文本库界面)。
我试过这样的东西
import subprocess
nw_usage = subprocess.Popen(['ifstat', '-i', 'wlan1'])
但它没有给我网络使用值。
我不知道如何从 ncurses 接口(interface)获取单个变量中的网络使用值。 (而且我感觉会有更好的方法来计算网络使用情况)
任何帮助或指导将是一个很大的帮助。
谢谢
最佳答案
我知道这个问题已经有几周了,但也许这个答案仍然有用:)
您可以从/proc/net/dev 中读取设备统计信息。在一个时间间隔内读取发送/接收的字节并计算差值。这是我一起破解的一些简单的 Python 脚本
import re
import time
# A regular expression which separates the interesting fields and saves them in named groups
regexp = r"""
\s* # a interface line starts with none, one or more whitespaces
(?P<interface>\w+):\s+ # the name of the interface followed by a colon and spaces
(?P<rx_bytes>\d+)\s+ # the number of received bytes and one or more whitespaces
(?P<rx_packets>\d+)\s+ # the number of received packets and one or more whitespaces
(?P<rx_errors>\d+)\s+ # the number of receive errors and one or more whitespaces
(?P<rx_drop>\d+)\s+ # the number of dropped rx packets and ...
(?P<rx_fifo>\d+)\s+ # rx fifo
(?P<rx_frame>\d+)\s+ # rx frame
(?P<rx_compr>\d+)\s+ # rx compressed
(?P<rx_multicast>\d+)\s+ # rx multicast
(?P<tx_bytes>\d+)\s+ # the number of transmitted bytes and one or more whitespaces
(?P<tx_packets>\d+)\s+ # the number of transmitted packets and one or more whitespaces
(?P<tx_errors>\d+)\s+ # the number of transmit errors and one or more whitespaces
(?P<tx_drop>\d+)\s+ # the number of dropped tx packets and ...
(?P<tx_fifo>\d+)\s+ # tx fifo
(?P<tx_frame>\d+)\s+ # tx frame
(?P<tx_compr>\d+)\s+ # tx compressed
(?P<tx_multicast>\d+)\s* # tx multicast
"""
pattern = re.compile(regexp, re.VERBOSE)
def get_bytes(interface_name):
'''returns tuple of (rx_bytes, tx_bytes) '''
with open('/proc/net/dev', 'r') as f:
a = f.readline()
while(a):
m = pattern.search(a)
# the regexp matched
# look for the needed interface and return the rx_bytes and tx_bytes
if m:
if m.group('interface') == interface_name:
return (m.group('rx_bytes'),m.group('tx_bytes'))
a = f.readline()
while True:
last_time = time.time()
last_bytes = get_bytes('wlan0')
time.sleep(1)
now_bytes = get_bytes('wlan0')
print "rx: %s B/s, tx %s B/s" % (int(now_bytes[0]) - int(last_bytes[0]), int(now_bytes[1]) - int(last_bytes[1]))
关于python - 如何以编程方式在 Linux 中查找网络使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24897608/