Zen
Zen

Reputation: 41

Python scapy: pcap file read, manipulate and write pcap

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.

Upvotes: 3

Views: 10810

Answers (2)

Cukic0d
Cukic0d

Reputation: 5411

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)

Upvotes: 2

cmh
cmh

Reputation: 10927

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)

Upvotes: 3

Related Questions