我正在尝试通过python代码计算wlan1接口上的总网络流量.到目前为止,我尝试使用ethtool,iftop,ifstat,nethogs,但是其中大多数工具都显示ncurses界面(基于文本的UI).我尝试过这样的事情import subprocessnw_usage = ...

我正在尝试通过python代码计算wlan1接口上的总网络流量.到目前为止,我尝试使用ethtool,iftop,ifstat,nethogs,但是其中大多数工具都显示ncurses界面(基于文本的UI).
我尝试过这样的事情
import subprocess
nw_usage = subprocess.Popen(['ifstat', '-i', 'wlan1'])
但这并不能给我网络使用价值.
我无法弄清楚如何从ncurses接口获取单个变量中的网络使用率值. (而且我感觉会有一些更好的方法来计算网络使用率)
任何帮助或指导将是一个很大的青睐.
谢谢
解决方法:
我知道这个问题已有数周之久,但也许这个答案仍然会有所帮助:)
您可以从/ 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中的网络使用情况


基础教程推荐
猜你喜欢
- OpenCV图像分割之分水岭算法与图像金字塔算法详解 2023-08-04
- Python-theano给出“…正在等待未知进程的现有锁…” 2023-11-11
- Python爬取当网书籍数据并数据可视化展示 2023-08-11
- CentOS7.4 安装Python3.5 2023-09-03
- python Windows和Linux路径表示问题 2023-09-04
- python读取文件夹中图片的图片名并写入excel表格 2023-08-11
- python列表中remove()函数的使用方法详解 2023-08-09
- 如何利用Python实现自动打卡签到的实践 2023-08-11
- Python数据结构列表 2023-08-09
- 详解Python中的字符串格式化 2023-08-04