Skip to main content
 首页 » 编程设计

python之监控模式下的 Scapy 嗅探

2024年10月24日9hnrainll

我使用 scapy 编写了一个 python 脚本来嗅探我的 WIFI 网络中的 TCP 数据包,并查看两个目的地之间是否存在连接。 如果我在不处于监控模式下时嗅探数据包,它会工作,但是当我在监控模式接口(interface)上嗅探时,它不起作用。

有什么想法可以让它发挥作用吗? 片段:

import logging 
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) 
from scapy.all import * 
import time 
 
class deferring_delete(object): 
def __init__(self, d): 
    self._dict = d 
def __enter__(self): 
    self._deletes = set() 
    return self 
def __exit__(self, type, value, tb): 
    for key in self._deletes: 
        try: 
            del self._dict[key] 
        except KeyError: 
            pass 
    del self._deletes 
def __delitem__(self, key): 
    if key not in self._dict: 
        raise KeyError(str(key)) 
    self._deletes.add(key) 
 
packet_count = 0 
packets = {} 
accepted = {} 
YOUR_IP = '10.0.0.1' 
FILTER = "tcp and host not {0}".format(YOUR_IP)  
 
def handshake_status(packet): 
    global packets,accepted,packet_count 
 
 
    flag = packet[0][1].sprintf('%TCP.flags%') 
    src_ip = packet[0][1].src 
    dst_ip = packet[0][1].dst 
 
    if flag == 'S': 
        packets[packet_count] = {'src_ip': src_ip, 'dst_ip': dst_ip, 'time': time.ctime() , 'flag': flag}  
        print "%s ==> %s SYN_SENT" % (src_ip, dst_ip) 
        packet_count += 1 
 
    if flag == 'SA': 
        for key , packet in packets.iteritems(): 
            if packet['src_ip'] == dst_ip: 
                accepted[key] = packet 
 
    if len(accepted) > 0: 
        with deferring_delete(packets) as p: 
            for key in accepted.keys(): 
                print "%s ==> %s ESTABLISHED" % (packets[key]['src_ip'], packets[key]['dst_ip']) 
                del p[key] 
 
        with deferring_delete(accepted) as a: 
            for key in accepted.keys(): 
                del a[key] 
 
 
if __name__ == '__main__': 
    sniff(iface="mon0", filter=FILTER ,prn=handshake_status) 

请您参考如下方法:

问题在于以下几行:

flag = packet[0][1].sprintf('%TCP.flags%') 
src_ip = packet[0][1].src 
dst_ip = packet[0][1].dst 

尝试如下重写它们:

flag = packet.getlayer(TCP).sprintf('%TCP.flags%') 
src_ip = packet.getlayer(IP).src 
dst_ip = packet.getlayer(IP).dst