我编写了简单的脚本,用于计算网络带宽。我使用 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()
我知道,代码并不是很好,它只是一个原型(prototype)。但我有下一个问题:我使用 root 权限启动了这个脚本,5 分钟后我的计算机挂起,它开始运行得非常非常缓慢。看来这个脚本占用了所有 RAM。我怎样才能解决这个问题 ?因为脚本应该至少可以运行 1 天。
最佳答案
我认为问题可能出在sniff
函数上,尝试用
def run(self):
sniff(filter="ip", prn=self.get_packet,store=False)
这样它就不会保存数据包并填充内存。
关于python - 为什么我的 Ubuntu 在启动 python 脚本后卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54065339/