iterate through pcap file packet for packet using python/scapy

不羁岁月 提交于 2021-02-20 09:04:33


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.

little example:

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
  # do anything 

Does anyone know the reason?


Try simply:

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

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 [...]