Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through pcap file packet for packet using python/scapy

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

Does anyone know the reason?

like image 839
crappidy Avatar asked Jun 08 '17 16:06

crappidy


1 Answers

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 [...]
like image 188
Pierre Avatar answered Sep 30 '22 22:09

Pierre