使用 python/scapy 遍历 pcap 文件包以获得数据包 [英] iterate through pcap file packet for packet using python/scapy

查看:129
本文介绍了使用 python/scapy 遍历 pcap 文件包以获得数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 python/scapy 遍历 pcap 文件包以获取数据包.该文件有多个协议.当前迭代是特定于协议的,因此如果下一个数据包来自另一个协议,则迭代进行跳转".我不知道为什么现在会这样.我想要一个包一个包,不管什么协议.

I want to iterate through a pcap file packet for packet using python/scapy. The file has multiple protocols. Current the iteration is protocol-specific, so the iteration makes a "jump" if the next packet is from another protocol. I don't know why it goes like this at the moment. I want packet for packet, no matter what protocol.

小例子:

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 

有人知道原因吗?

推荐答案

简单地尝试:

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

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

Using rdpcap() creates a list in memory, while PcapReader() creates a generator, packets are read when needed and not stored in memory (which makes it possible to process huge PCAP files).

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

If you need a list for some reason, do:

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

这篇关于使用 python/scapy 遍历 pcap 文件包以获得数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆