iterate through pcap file packet for packet using python/scapy

断了今生、忘了曾经 提交于 2021-02-20 09:08:15

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/44440738/iterate-through-pcap-file-packet-for-packet-using-python-scapy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!