我正在尝试编写一个可以监控网络流量的代码,有没有办法编写可以监控进出流量(带宽)的代码,并能够在python中看到实时带宽使用情况?
答案 0 :(得分:3)
假设你使用Linux:
阅读/sys/class/net/{INTERFACE_NAME}/statistics/tx_bytes
& /sys/class/net/{INTERFACE_NAME}/statistics/rx_bytes
获得被发送的&收到的字节。然后你可以计算一个时间步和瞧之间的差异:你有数据速率。
有关tx / rx文件的说明,请参阅kernel documentation。
编辑: 快速& 脏实现只是为了表明这个想法:
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))