Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python scapy: pcap file read, manipulate and write pcap

Tags:

python

pcap

scapy

I want to read a pcap file using python scapy, manipulate the TCP payload (e.g. delete the current payload and replace it with 0s) and write the manipulated packets to a new pcap file.

like image 964
Zen Avatar asked Feb 19 '26 05:02

Zen


2 Answers

Here's a solution using pypcap and dpkt. It assumes that IP is the L2 protocol.

import dpkt
from dpkt.ip import IP
from dpkt.tcp import TCP

for ts, raw_pkt in pcap.pcap(file_path):
    ip = IP(raw_pkt[14:])
    if(type(ip) != IP):
        continue
    tcp = ip.data
    if(type(tcp) != TCP):
        continue
    do_something_with(tcp.data)
like image 124
cmh Avatar answered Feb 20 '26 18:02

cmh


FTR, to answer the op question,

from scapy.all import *
with PcapWriter("output.pcap", sync=True) as outs:
    with PcapReader("input.pcap") as ins:
        for pkt in ins:
            if TCP in pkt:
                pkt[TCP].remove_payload()
            outs.write(pkt)
like image 45
Cukic0d Avatar answered Feb 20 '26 18:02

Cukic0d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!