我正在尝试编写一个可以监视网络流量的代码,有什么方法可以编写这样的代码来监视进出的流量(带宽),并且能够看到python中的实时带宽使用情况吗?
发布于 2017-01-03 16:39:00
假设您使用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))https://stackoverflow.com/questions/41446493
复制相似问题