使用Python/Scapy逐个迭代读取pcap文件中的数据包

7
我希望使用Python/Scapy遍历pcap文件中的每一个数据包。该文件包含多种协议。目前,迭代是基于协议的,因此如果下一个数据包来自另一个协议,则会发生“跳转”。我目前不知道为什么会这样。我想要逐个数据包进行迭代,无论协议如何。
小例子:
data = 'new.pcap'
zz = rdpcap(data)
sessions = zz.sessions()

for session in sessions:
  for packet in sessions[session]:
    eth_src = packet[Ether].src 
    eth_type = packet[Ether].type

if eth_src == "00:22:97:04:06:b9" and eth_type == 0x8100:       
  # do anything
elif eth_src == "00:22:97:04:06:b9" and eth_type == 0x22f0: 
  # do anything
else:
  # do anything 

有人知道原因吗?

1个回答

15

尝试简单地:

for pkt in PcapReader('new.pcap'):
    eth_src = pkt[Ether].src 
    eth_type = pkt[Ether].type
    if [...]

使用rdpcap()创建一个内存中的列表,而PcapReader()创建一个生成器,数据包在需要时读取,不会存储在内存中(这使得处理巨大的PCAP文件成为可能)。

如果出于某种原因需要一个列表,则执行以下操作:

packets = rdpcap('new.pcap')
for pkt in packets:
    eth_src = pkt[Ether].src 
    eth_type = pkt[Ether].type
    if [...]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接