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

时间:2014-07-22 20:52:02

标签: python linux network-programming ubuntu-12.04 performance-testing

我试图通过python代码计算wlan1接口上的总网络流量。现在我尝试了ethtooliftopifstatnethogs,但这些工具中的大多数都显示了ncurses接口(文本库UI)。

我试过这样的事情

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

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

我无法弄清楚如何从ncurses接口获取单个变量中的网络使用值。 (我感觉会有更好的方法来计算网络使用情况)

任何帮助或方向都将是一个很大的帮助。

由于

2 个答案:

答案 0 :(得分:3)

我知道问题已经过了几个星期了,但也许这个答案仍然有用:)

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

答案 1 :(得分:0)

可能有更好的方法,但我用来估算命令行网络费率的丑陋办法是:

ifconfig; sleep 10; ifconfig;

然后只需减去&#34; TX字节&#34; (在传输的情况下)在相关接口上并除以10(睡眠时间)进行粗略估计,以 B 每秒的速度进行。