如何在Linux中以编程方式查找网络使用情况

3 投票
2 回答
3415 浏览
提问于 2025-04-18 14:20

我正在尝试通过一段Python代码来计算接口的总网络流量。到目前为止,我试过了ethtooliftopifstatnethogs,但这些工具大多数都是以文本界面显示的。

我试过类似这样的代码:

import subprocess
nw_usage = subprocess.Popen(['ifstat', '-i', 'wlan1'])

但是它没有给我网络使用值。

我搞不清楚如何从这些文本界面中获取网络使用值到一个变量里。(而且我感觉可能有更好的方法来计算网络使用情况)

任何帮助或指导都将非常感谢。

谢谢

2 个回答

0

可能有更好的方法,但我用过一个比较笨的方法来从命令行估算网络速度:

ifconfig; sleep 10; ifconfig;

然后只需要在相关的网络接口上减去“TX字节”(如果是发送的话),再除以10(这是等待的时间),就能大致算出每秒的字节数。

5

我知道这个问题已经有几周了,但也许这个回答还是能帮到你 :)

你可以从 /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]))

撰写回答