You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scapy被动扫描脚本无法实时输出,需实现运行时动态打印主机信息

解决Scapy被动扫描动态实时输出问题

原脚本的核心问题是sniff()函数为阻塞执行逻辑,所有包处理与打印操作都要等sniff()结束(超时或手动中断)后才会运行,因此必须等待任务终止才会输出结果。要实现动态逐行打印,需要把ARP包的处理、去重和打印逻辑移到sniff()的prn回调函数中,实时处理每一个捕获到的包。

修改后的完整代码

from scapy.all import sniff, ARP

# 跟踪已发现的主机:key为IP,value存储MAC地址和出现次数
discovered_hosts = {}
# 标记表头是否已打印,避免重复输出
header_printed = False

def update_and_print_host(src_ip, src_mac):
    global header_printed
    # 更新主机计数或添加新主机
    if src_ip in discovered_hosts:
        discovered_hosts[src_ip]["count"] += 1
    else:
        discovered_hosts[src_ip] = {"mac": src_mac, "count": 1}
    
    # 首次执行时打印表头
    if not header_printed:
        print("Interface: eth0\t\tMode: Passive\t\tFound 0 hosts")        
        print("----------------------------------------------------------------------------")
        print("MAC\t\t\t\tIP\t\t\tHost Activity")
        print("----------------------------------------------------------------------------")
        header_printed = True
    
    # 更新已发现主机数量(用回车覆盖当前行)
    print(f"\rInterface: eth0\t\tMode: Passive\t\tFound {len(discovered_hosts)} hosts", end="")
    
    # 清屏后重新打印所有主机的最新状态(确保显示内容实时准确)
    print("\033[H\033[J", end="")
    print(f"Interface: eth0\t\tMode: Passive\t\tFound {len(discovered_hosts)} hosts")        
    print("----------------------------------------------------------------------------")
    print("MAC\t\t\t\tIP\t\t\tHost Activity")
    print("----------------------------------------------------------------------------")
    for ip, info in discovered_hosts.items():
        print(f"{info['mac']}\t\t{ip}\t\t{info['count']}")

def arp_packet_handler(packet):
    if ARP in packet and packet[ARP].op == 2:  # 仅处理ARP响应包(op=2为响应)
        src_mac = packet[ARP].hwsrc
        src_ip = packet[ARP].psrc
        update_and_print_host(src_ip, src_mac)

def passive_scan(interface):
    # 启动sniff,实时处理每个符合条件的包
    sniff(iface=interface, prn=arp_packet_handler, timeout=10000)

# 调用示例
passive_scan("eth0")

修改说明

  • 用discovered_hosts字典跟踪已发现的主机,既避免重复记录,又能维护每个IP的出现次数
  • 将ARP包的处理逻辑放到arp_packet_handler回调函数中,每捕获到ARP响应包就实时更新主机信息
  • 通过header_printed控制表头仅打印一次,避免重复输出
  • 采用清屏后重新打印的方式,确保显示的所有主机信息都是最新状态;如果不需要清屏,也可以改为仅在新增主机时打印,计数更新时忽略或单独更新对应行

内容的提问来源于stack exchange,提问作者hemang joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:10:36