2014-05-01 80 views
1

我编写了这个程序来嗅探网络中的icmp数据包并打印出那里的源地址。代码如下:运行Scapy嗅探函数时出错

from scapy.all import * 

def fun_callback(pkt): 
    print str(pkt.payload.src) 
sniff(prn = fun_callback, filter = 'icmp', timeout =5) 

运行此程序后,我收到此错误。

[[email protected] 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 
[[email protected] icmp]# 

为什么会发生这种例外情况?

+0

似乎没有src属性。再次检查文档 – Moj

+1

当数据包中的特定字段为空或不存在时,通常会发生这种情况。在这种情况下,你的数据包似乎没有源字段。 – TheCreator232

回答

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))