Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python stop sniffing upon specific condition

I found some questions regarding an object deleting itself. But nowhere mentioned a suitable example where such action is required. But take the below example.

from scapy.all import *

class x():
    def me(self):
        self.i=0
        sniff(iface="em1", filter='tcp', prn=self.my_callback)

    def my_callback(self, pkt):
        print pkt.summary()
        self.i+=1
        if self.i>10:
            self.__del__()

    def __del__(self):
        print self
        return

y=x()
y.me()
print y

In this case, the sniff function will continue infinitely. I want to stop it and delete the object if I receive 10 pkts. So the deletion of the object should be initiated from within.

How can I do that?

like image 680
RatDon Avatar asked Dec 11 '22 00:12

RatDon


2 Answers

If the goal is to stop sniff when you receive a specific packet from a specific IP, then the correct approach is to pass in a stop_filter to the sniff function, as specified in the documentation, copied below.

>>> print sniff.__doc__
Sniff packets
sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets

  count: number of packets to capture. 0 means infinity
  store: wether to store sniffed packets or discard them
    prn: function to apply to each packet. If something is returned,
         it is displayed. Ex:
         ex: prn = lambda x: x.summary()
lfilter: python function applied to each packet to determine
         if further action may be done
         ex: lfilter = lambda x: x.haslayer(Padding)
offline: pcap file to read packets from, instead of sniffing them
timeout: stop sniffing after a given time (default: None)
L2socket: use the provided L2socket
opened_socket: provide an object ready to use .recv() on
stop_filter: python function applied to each packet to determine
             if we have to stop the capture after this packet
             ex: stop_filter = lambda x: x.haslayer(TCP)

Here is some sample code that will stop sniffing on a packet from a particular IP.

from scapy.all import *

def stopfilter(x):
     if x[IP].dst == '23.212.52.66':
         return True
     else
         return False

sniff(iface="wlan0", filter='tcp', stop_filter=stopfilter)
like image 164
merlin2011 Avatar answered Dec 13 '22 12:12

merlin2011


sniff(other_args=other_values, count=10)
#                              ^^^^^

The solution here isn't to destroy the object. If you somehow managed to destroy the object, scapy would just crash horribly or do crazy things when it tried to use a destroyed object.

like image 31
user2357112 supports Monica Avatar answered Dec 13 '22 12:12

user2357112 supports Monica