Python停止嗅探特定条件

Rat*_*Don 3 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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,该sniff功能将无限延续.我想停止它并删除object我收到的10 pkts.所以删除对象应该从内部开始.

我怎样才能做到这一点?

mer*_*011 6

如果目标是在sniff从特定IP接收特定数据包时停止,那么正确的方法是将a传递stop_filtersniff下面复制的文档中指定的函数.

>>> 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)
Run Code Online (Sandbox Code Playgroud)

下面是一些示例代码,它将停止嗅探来自特定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)
Run Code Online (Sandbox Code Playgroud)


use*_*ica 5

sniff(other_args=other_values, count=10)
#                              ^^^^^
Run Code Online (Sandbox Code Playgroud)

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