Python scapy显示ping(echo)请求的ip

2024-05-13 21:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想获取并打印ping请求的源地址。 我有以下脚本:

pkt = sniff(filter="icmp", timeout =15, count = 15)
if pkt[ICMP].type == '8':
    print pkt[IP].src

当数据包到达时,脚本崩溃

 AttributeError:'list' object has no attribute 'type'

但是在scapy控制台上我可以清楚地看到这个存在!

>>>packet=IP()/ICMP()/"AAAAAA"
>>>packet[ICMP].type
8
>>>

有什么想法吗??

我为了测试的目的改变了(!)我的脚本如下:

pkts=sniff(filter="icmp", timeout=120,count=15)

for packet in pkts:
    if packet.haslayer(IP) and str(packet.getlayer(IP).src)=="127.0.0.1"
       print "packet arrived"
           if packet.haslayer(ICMP) and str(packet.getlayer(ICMP).type)=="8":
                print(packet[IP].src)

执行ping之后,执行上述操作:

ping localhost -c 3

产生以下尴尬的结果:

packet arrived
127.0.0.1
packet arrived
127.0.0.1
packet arrived
packet arrived
packet arrived
127.0.0.1
packet arrived
127.0.0.1
packet arrived
packet arrived
packet arrived
127.0.0.1
packet arrived
127.0.0.1
packet arrived

我们可以多次忽略“数据包到达”,因为其他数据包也正在到达我的主机。但是为什么我在发送3个echo请求时看到127.0.0.1的6倍呢?即使我移除for循环,也会发生相同的结果。


Tags: ipsrc脚本ifpackettypefilterping
2条回答

您有多个数据包,因此可以索引或遍历:

from scapy.all import *
pkts = sniff(filter="icmp", timeout =15,count=15)

for packet in pkts:
     if  str(packet.getlayer(ICMP).type) == "8": 
        print(packet[IP].src)

或者使用索引来获取forst包:

from scapy.all import *
pkts = sniff(filter="icmp", timeout =15,count=15)

if pkts  and str(pkts[0].getlayer(ICMP).type) == "8": 
        print(pkts[0][IP].src)

sniff()返回的不是一个数据包列表,即使您可以像遍历列表一样遍历它。请参见以下示例:

>>> from scapy.all import *
>>> pkts = sniff(count = 15)
>>> pkts
<Sniffed: TCP:4 UDP:4 ICMP:0 Other:7>
>>> pkts[TCP]
<TCP from Sniffed: TCP:4 UDP:0 ICMP:0 Other:0>
>>>

如果sniff()只是返回一个数据包列表,那么示例中的pkt[ICMP]将永远不起作用。pkt[ICMP]的作用是检索pkt中所有ICMP数据包的列表。

相关问题 更多 >