Python停止嗅探特定条件

时间:2015-03-04 04:41:06

标签: python object scapy packet-sniffers

我发现了一些关于自动删除对象的问题。但是没有提到需要这种行动的合适例子。但请看下面的例子。

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函数将无限延续。如果收到object,我想停止并删除10 pkts。所以删除对象应该从内部开始。

我该怎么做?

2 个答案:

答案 0 :(得分:6)

如果目标是在收到来自特定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)

答案 1 :(得分:5)

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

这里的解决方案并不是要破坏对象。如果你以某种方式设法摧毁了这个物体,那么当它试图使用被摧毁的物体时,scapy就会崩溃或者发生疯狂的事情。