简体   繁体   中英

Why does my Ubuntu freeze after launching python script?

I wrote simple script, that calculates bandwidth of my network. I used library scapy to sniff all incoming traffic and calculate speed. Here is my code, that sniffer traffic:

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

This code calculates bandwidth in Mb/s every 10 seconds

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()

I know, that the code is not really good, it is just a prototype. But I have next problem: I launched this script with root privileges and after 5 minutes my computer hangs, it started to work very-very slowly. It seems that this script took all RAM. How can I fix this ? because script should work at least 1 day.

I think the problem may lay in the sniff function, try to call with

def run(self):
    sniff(filter="ip", prn=self.get_packet,store=False)

so that it doesn't save packets and fill the ram.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM