如何使用VLAN层读取数据包

时间:2020-04-30 17:46:22

标签: python wireshark pcap vlan

我正在用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。我已经尝试过将“ layers =”参数添加到load_savefile中,但这没有用。有什么办法解决吗?

1 个答案:

答案 0 :(得分:1)

这就是我最终测试事物的方式。我从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

我们可以使用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