python网络流量监视器

时间:2017-01-03 15:08:45

标签: python-3.x network-programming

我正在尝试编写一个可以监控网络流量的代码,有没有办法编写可以监控进出流量(带宽)的代码,并能够在python中看到实时带宽使用情况?

1 个答案:

答案 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))