【问题标题】:Packet Count Using Scapy in Python在 Python 中使用 Scapy 进行数据包计数
【发布时间】:2021-08-05 11:46:31
【问题描述】:

我正在使用以下方式从特定 IP 地址捕获 ICMP 数据包:

import scapy.all from *

sniff(filter="icmp and src host 192.168.100.3 and dst host 192.168.100.2", prn=lambda x: x.sprintf("%IP.proto% packets from %IP.src% to %IP.dst%"))

我得到以下输出:

icmp packets from 192.168.100.3 to 192.168.100.2
icmp packets from 192.168.100.3 to 192.168.100.2
icmp packets from 192.168.100.3 to 192.168.100.2
icmp packets from 192.168.100.3 to 192.168.100.2
icmp packets from 192.168.100.3 to 192.168.100.2
...

但是,我只想显示捕获的数据包总数 实时,即

Total icmp packets from 192.168.100.3 to 192.168.100.2 is <total_packets>

上面的这行也应该定期更新,即我只希望在我的输出中始终使用这行。请指导。

【问题讨论】:

    标签: python scapy packet-sniffers


    【解决方案1】:

    首先,你需要修改这一行:

    sniff(filter="icmp and src host 192.168.100.3 and dst host 192.168.100.2", prn=lambda x: x.sprintf("%IP.proto% packets from %IP.src% to %IP.dst%"))
    

    lambda x: x.sprintf("%IP.proto% packets from %IP.src% to %IP.dst%" 函数针对每个请求运行

    比如:

    import os
    counter = 0
    def dealwithpackets(x):
        global counter
        os.system("cls")
        ips = x.sprintf("Total icmp packets from %IP.src% to %IP.dst%")
        counter += 1
        print(ips + "is" + str(counter))
        
    sniff(filter="icmp and src host 192.168.100.3 and dst host 192.168.100.2", prn=lambda x: dealwithpackets(x))
    

    在 Windows 上使用 os.system("cls"),在 Linux 和 macOS 上使用 os.system("clear")

    【讨论】:

    • 谢谢。我只想提两件事:第一:在 print() 语句中将 counter 包装在 str() 中。第二:在 Linux 中将“cls”替换为“clear”。不过不知道windows。
    • 另外,counter+=1 应该在 print 语句的上方,否则会显示少一个数据包。
    • @MRA1412 打印声明是对的,这是一个疏忽
    • 在 Windows 中确实是 cls
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 2013-09-11
    • 2021-03-19
    • 2014-12-26
    • 1970-01-01
    相关资源
    最近更新 更多