Python 在特定条件下停止嗅探

Python stop sniffing upon specific condition

我发现了一些关于删除自身的对象的问题。但没有地方提到需要采取此类行动的合适示例。但以下面的例子为例。

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

在这种情况下,sniff函数将无限继续。如果收到 10 pkts,我想停止它并删除 object。所以对象的删除应该从内部发起。

我该怎么做?

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

这里的解决方案不是销毁对象。如果您以某种方式设法销毁了该对象,scapy 会在尝试使用已销毁的对象时发生可怕的崩溃或做出疯狂的事情。

如果目标是在收到来自特定 IP 的特定数据包时停止 sniff,那么正确的方法是将 stop_filter 传递给 sniff 函数,如文档中所述,复制如下。

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

这是一些示例代码,可以停止嗅探来自特定 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)