Wyl*_*lie 0 network-programming python-3.x
我正在尝试编写一个可以监控网络流量的代码,有没有办法编写可以监控进出流量(带宽)并能够在 python 中查看实时带宽使用情况的代码?
假设您使用 Linux:
读取/sys/class/net/{INTERFACE_NAME}/statistics/tx_bytes&/sys/class/net/{INTERFACE_NAME}/statistics/rx_bytes以获取发送和接收的字节。然后您可以计算时间步长和瞧之间的差异:您有数据速率。有关 tx/rx 文件的说明,请参阅内核文档。
编辑:快速和肮脏的实现只是为了展示这个想法:
import time
def transmissionrate(dev, direction, timestep):
"""Return the transmisson rate of a interface under linux
dev: devicename
direction: rx (received) or tx (sended)
timestep: time to measure in seconds
"""
path = "/sys/class/net/{}/statistics/{}_bytes".format(dev, direction)
f = open(path, "r")
bytes_before = int(f.read())
f.close()
time.sleep(timestep)
f = open(path, "r")
bytes_after = int(f.read())
f.close()
return (bytes_after-bytes_before)/timestep
devname = "wlo1"
timestep = 2 # Seconds
print(transmissionrate(devname, "rx", timestep))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7728 次 |
| 最近记录: |