我正在用Python编写一个程序,从.pcap文件中读取和解码GOOSE数据包。到目前为止,我已经能够用Pypcapfile库来读取数据包。
from pcapfile import savefile
file = input("Enter the name of the pcap file: ")
try:
pcap = open(file, 'rb')
except IOError:
print("No file with name \"{}\" was found.\n".format(file))
return
capfile = savefile.load_savefile(pcap, verbose=True)
print(capfile)
终端。
Enter the name of the pcap file: goose2.pcap
[+] attempting to load goose2.pcap
[+] found valid header
[+] loaded 8023 packets
[+] finished loading savefile.
b'little'-endian capture file version 2.4
microsecond time resolution
snapshot length: 262144
linklayer type: LINKTYPE_ETHERNET
number of packets: 8023
问题是当我用包含VLAN头的数据包(只有两个字节)来测试我的代码时,它说pcap文件有0个数据包。
Enter the name of the pcap file: vlan.pcap
[+] attempting to load vlan.pcap
[+] found valid header
[+] loaded 0 packets
[+] finished loading savefile.
b'big'-endian capture file version 2.4
nanosecond time resolution
snapshot length: 65535
linklayer type: LINKTYPE_ETHERNET
number of packets: 0
我的整个代码都是围绕着Pypcapfile库写的 所以我想避免从头开始使用另一个库,比如Scapy。我已经尝试过在load_savefile中加入 "layer="参数,但没有成功。有什么方法可以解决这个问题吗?
下面是我如何在我的终端上进行测试的。我从wireshark wiki中抓取了vlan捕获的样本并进行了解压。
$ curl -o vlan.cap.gz 'https://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=vlan.cap.gz'
$ gunzip vlan.cap.gz
我们可以用e. g. tshark
来验证这个捕获包括VLAN标记的数据包。
$ tshark -r vlan.cap -V
Frame 1: 1518 bytes on wire (12144 bits), 1518 bytes captured (12144 bits)
[...]
Ethernet II, Src: AniCommu_40:ef:24 (00:40:05:40:ef:24), Dst: 3com_9f:b1:f3 (00:60:08:9f:b1:f3)
[...]
Type: 802.1Q Virtual LAN (0x8100)
802.1Q Virtual LAN, PRI: 0, DEI: 0, ID: 32
000. .... .... .... = Priority: Best Effort (default) (0)
...0 .... .... .... = DEI: Ineligible
.... 0000 0010 0000 = ID: 32
Type: IPv4 (0x0800)
Internet Protocol Version 4, Src: 131.151.32.129, Dst: 131.151.32.21
我可以用这个打开 pcapfile
模块。
$ pip install --user Pypcapfile
$ python
>>> import pcapfile.savefile
>>> with open('vlan.cap', 'rb') as fd:
... capfile = pcapfile.savefile.load_savefile(fd, layers=2)
...
>>> capfile
b'little'-endian capture file version 2.4
microsecond time resolution
snapshot length: 65535
linklayer type: LINKTYPE_ETHERNET
number of packets: 395
>>> capfile.packets[0]
ethernet from b'00:40:05:40:ef:24' to b'00:60:08:9f:b1:f3' type unknown
但它看起来像 pcapfile
没有针对VLAN帧的特定解码器。
帧的解码器。dpkt
模块的效果很好。
>>> import dpkt
>>> fd = open('vlan.cap', 'rb')
>>> capfile = dpkt.pcap.Reader(fd)
>>> ts, buf = next(capfile)
>>> pkt = dpkt.ethernet.Ethernet(buf)
>>> pkt.vlan_tags
[VLANtag8021Q(pri=0, cfi=0, id=32)]
正如 scapy
:
>>> import scapy.all
>>> capfile = scapy.all.rdpcap('vlan.cap')
>>> capfile[0].vlan
32