我写了一个简单的脚本,用于计算网络带宽。我使用库Scapy嗅探所有传入流量并计算速度。这是我的代码,嗅探流量:
from time import sleep
from threading import Thread, Event
from scapy.all import *
class Sniffer(Thread):
def __init__(self):
Thread.__init__(self)
self.count_downloaded_bytes = 0
def run(self):
sniff(filter="ip", prn=self.get_packet)
def get_packet(self, packet):
self.count_downloaded_bytes += len(packet) # calculate size of packets
def get_count_downloaded_bytes(self):
count_d_bytes = self.count_downloaded_bytes
self.count_downloaded_bytes = 0
return count_d_bytes # returns size of downloaded data in bytes
此代码每10秒以Mb / s为单位计算带宽
class NetworkSpeed(Thread):
def __init__(self):
Thread.__init__(self)
self.sniffer = Sniffer() # create seconds thread, that sniffs traffic
self.start()
def calculate_bandwidth(self, count_downloaded_bytes, duration):
download_speed = (count_downloaded_bytes / 1000000 * 8) / duration
print('download_speed = ', download_speed)
def run(self):
counter = 0
self.sniffer.start()
while True:
if counter == 10:
self.calculate_bandwidth(self.sniffer.get_count_downloaded_bytes(), 10)
counter = 0
counter += 1
sleep(1)
network_speed = NetworkSpeed()
我知道,代码不是很好,它只是一个原型。但是我还有另一个问题:我以root特权启动了此脚本,并且在计算机挂起5分钟后,它开始非常缓慢地工作。该脚本似乎占用了所有RAM。我怎样才能解决这个问题 ?因为脚本应该至少工作1天。
答案 0 :(得分:1)
我认为问题可能出在sniff
函数中,请尝试使用
def run(self):
sniff(filter="ip", prn=self.get_packet,store=False)
这样它就不会保存数据包并填充内存。