Python - save packets to pcapng file

996 views Asked by At

My code creates a couple of packets using scapy and should save them to pcapng files. However, I couldn't find any way to save the files as pcapng. I tried using Scapy's PcapWriter and saving the files to sniff.pcapng, but the result is a pcap file with a pcapng extension. Also tried looking for modules to convert the existing pcap file to pcapng, but couldn't find anything. (Found this python-pcapng module, but couldn't find any documentation about how to save a file I read)

2

There are 2 answers

0
Nadav Barghil On

I would take a look at this from the library you linked to. Seems like it is an example of creating a pcapng given a packet.

0
Adir Bruchim On

Thanks Nadav! I had to make some changes to make it work, So I'm adding the code in case anyone else will need it.

import pcapng.blocks as blocks
from pcapng import FileWriter
from scapy.all import *

SHB_INTERFACE_OPTIONS = {"if_description": "Hand-rolled","if_os": "Python"}
SHB_HEADER_OPTIONS = {"shb_hardware": "artificial", "shb_os": "python", "shb_userappl": "python-pcapng"}

shb = blocks.SectionHeader(options=conf.SHB_HEADER_OPTIONS)
shb.new_member(blocks.InterfaceDescription, link_type=1, options=conf.SHB_INTERFACT_OPTIONS)
    with open(f'{pcap_path}ng', 'ab') as file_obj:
        writer = FileWriter(file_obj, shb)
        orig_packets = rdpcap(pcap_path)
        for packet in orig_packets:
            spb = shb.new_member(blocks.SimplePacket)
            spb.packet_data = bytes(packet)
            writer.write_block(spb)