Python在特定条件下停止嗅探

2024-10-06 16:17:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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。因此,应该从内部开始删除对象。

我该怎么做?


Tags: 对象fromimportselfmydefcallbackall
2条回答

如果目标是在从特定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)
sniff(other_args=other_values, count=10)
#                              ^^^^^

这里的解决办法不是摧毁这个物体。如果你以某种方式摧毁了这个物体,当它试图使用一个被摧毁的物体时,scapy就会崩溃或者做一些疯狂的事情。

相关问题 更多 >