问题
I am trying to simply parse through data in a packet capture. I've taken examples just to see if I could compile and I end up with an error. Below is the code.
import dpkt
import sys
f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
ip = eth.data
tcp = ip.data
f.close()
The error I get is the following:File "inspection.py", line 15, in tcp = ip.data
AttributeError: 'str' object has no attribute 'data'
Any help would be appreciated.
回答1:
The call to dpkt.ethernet.Ethernet(buf)
returned a string because the Ethernet class was unable to unpack buf
. A likely cause for this is that your pcap file does not have ethernet as its layer 2 protocol. You can load the pcap into Wireshark to confirm this.
The following script attempts to check the datalink field of the pcap file and use an appropriate layer 2 dpkt class to decode the frame:
import dpkt
import sys
f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
if pcap.datalink() == dpkt.pcap.DLT_LINUX_SLL:
l2 = dpkt.sll.SLL(raw_pkt)
else:
l2 = dpkt.ethernet.Ethernet(buf)
ip = l2.data
tcp = ip.data
回答2:
What I did to solve the problem was:
if ip.p == 6:
tcp = dpkt.tcp.TCP(ip.data)
来源:https://stackoverflow.com/questions/9330686/parsing-pcap-in-python-2-6