Justin Carrey
Justin Carrey

Reputation: 3851

reading and writing packets python-scapy

I am trying to read packets one by one from multiple files and write them to files in different folder(using same file names). I am using this program:

import os, os.path
from scapy.all import*

i=0
filename = ''

def callback_func(pkt):
    wrpcap("/home/new/"+filename,pkt)

files_in_dir = os.listdir("/home/packets/info/sub1")
for file in files_in_dir:
    filename = str(file)
    sniff(prn = callback_func, offline = file)  

In this program, i am reading a file from /home/packets/info/sub1 directory, read all the packets in that file one by one using sniff(), write all those packets in that file to another file with same filename in different directory using wrpcap, /home/new/.

Scapy is overwriting the previous packet with the current one. Is there a way to append packets to the file rather than overwriting? Thanks

Upvotes: 1

Views: 5546

Answers (1)

Mike Pennington
Mike Pennington

Reputation: 43081

All you've asked scapy to do is overwrite... to append, you need to do something like this...

import os, os.path
from scapy.all import *

i=0
filename = ''

ORIG_DIR = '/home/packets/info/sub1'
files_in_dir = os.listdir(ORIG_DIR)
for file in files_in_dir:
    filename = str(file)
    paks = rdpcap(ORIG_DIR+filename)  # Read original packets
    paks.extend(sniff(offline=file))      # Append new packets to original pak list
    wrpcap('/home/new/'+filename, paks)   # write new pak list to file

Upvotes: 2

Related Questions