Python Scapy wrpcap - How do you append packets to a pcap file?

The wrpcap() function can be used to append if you include the keyword argument append=True. For example:

pkt = IP()
wrpcap('/path/to/filename.pcap', pkt, append=True)
pkt2 = IP()
wrpcap('/path/to/filename.pcap', pkt2, append=True)

rdpcap('/path/to/filename.pcap')

<filename.pcap: TCP:0 UDP:0 ICMP:0 Other:2>

Side note: wrpcap opens and closes the file handle with each call. If you have an open file handle to the pcap file, it will be closed after a call to wrpcap().


There is a way to do what you want, but it means either:

  • [Memory hog with one big pcap]: Read the existing pcap from disk with rdpcap() into a scapy PacketList() and then writing frames to the PacketList as they are received. You can selectively save intermediate PacketList to the pcap at will, but I don't think there is anything like an append capability in scapy's wrpcap(). As you mentioned, this technique also means that you are keeping the entire PacketList in memory until completion.

  • [Glue individual pcap files together]: Only keep small snapshots of packets in memory... you should save pcap snapshots on a per-X-minute basis to disk, and then aggregate those individual files together when the script finishes.

You can combine pcap files in linux with mergecap from the wireshark package... The following command will combine pak1.pcap and pak2.pcap into all_paks.pcap:

mergecap -w all_paks.pcap pak1.pcap pak2.pcap

As for dpkt, I looked through their source, and it might be able to incrementally write packets, but I can't speak for how stable or maintained their code base is... it looks a bit neglected from the commit logs (last commit was January 9th 2011).


For posterity, PcapWriter or RawPcapWriter looks to be the easier way to deal with this in scapy 2.2.0. Couldn't find much documentation other than browsing the source though. A brief example:

from scapy.utils import PcapWriter

pktdump = PcapWriter("banana.pcap", append=True, sync=True)

...
pktdump.write(pkt)
...