我写了这个程序来嗅探网络中的icmp数据包并在那里打印源地址。代码如下:
from scapy.all import *
def fun_callback(pkt):
print str(pkt.payload.src)
sniff(prn = fun_callback, filter = 'icmp', timeout =5)
运行此程序后,我收到此错误。
[root@localhost icmp]# python test.py
WARNING: Failed to execute tcpdump. Check it is installed and in the PATH
WARNING: No route found for IPv6 destination :: (no default route?)
192.168.134.131
192.168.134.131
192.168.134.2
192.168.134.2
fe80::20c:29ff:fee4:a130
134.160.38.1
192.168.134.131
Traceback (most recent call last):
File "test.py", line 5, in <module>
sniff(prn = fun_callback, filter = 'icmp', timeout =5)
File "/usr/lib/python2.7/site-packages/scapy/sendrecv.py", line 586, in sniff
r = prn(p)
File "test.py", line 4, in fun_callback
print str(pkt.payload.src)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 176, in __getattr__
fld,v = self.getfield_and_val(attr)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 172, in getfield_and_val
return self.payload.getfield_and_val(attr)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 172, in getfield_and_val
return self.payload.getfield_and_val(attr)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 1057, in getfield_and_val
raise AttributeError(attr)
AttributeError: src
[root@localhost icmp]#
为什么会发生这种异常?
答案 0 :(得分:1)
您已使用没有src
属性的有效负载嗅探了数据包。如果您想快速修复代码,请写:
def fun_callback(pkt):
if hasattr(pkt.payload, "src"):
print str(pkt.payload.src)
问题是,你真的不知道pkt.payload
会是什么。如果您想要更好的解决方案,请尝试以下方法:
def fun_callback(pkt):
if IP in pkt: print pkt[IP].src
elif IPv6 in pkt: print pkt[IPv6].src
或者更好,.sprintf()
:
sniff(prn=lambda pkt: pkt.sprintf("{IP:%IP.src%}{IPv6:%IPv6.src%}"),
filter='icmp', timeout=5))