2

I have a program that can scan a pcap file using pyshark.FileCapture and then print the filtered packets.

I want to save those packets to a new pcap file.

Code:

import pyshark
import os
import sys
from scapy.all import *

def save_to_pcap(cap, filename):
    new_cap = PcapWriter(filename, append=True)

    for packet in cap:
        new_cap.write(packet.get_raw_packet())

def load_pcap(filter_str, path):
    cap = pyshark.FileCapture(path, display_filter=filter_str)
    return cap

def main():
    cap = load_pcap('http', 'file.pcap')
    cap
    save_to_pcap(cap, 'results.pcap')

main()

I tried using scapy, but save_to_pcap() function does not work and this exception pops up:

Traceback (most recent call last):
  File "SharkAn.py", line 116, in <module>
    main()
  File "SharkAn.py", line 108, in main
    save_to_pcap(cap, filename)
  File "SharkAn.py", line 81, in save_to_pcap
    pcap = rdpcap(cap)
  File "C:\Users\Gal\AppData\Local\Programs\Python\Python37\lib\site-packages\scapy\utils.py", line 860, in rdpcap
    with PcapReader(filename) as fdesc:
  File "C:\Users\Gal\AppData\Local\Programs\Python\Python37\lib\site-packages\scapy\utils.py", line 883, in __call__
    filename, fdesc, magic = cls.open(filename)
  File "C:\Users\Gal\AppData\Local\Programs\Python\Python37\lib\site-packages\scapy\utils.py", line 914, in open
    magic = fdesc.read(4)
AttributeError: 'FileCapture' object has no attribute 'read'
Tomer Katzir
  • 53
  • 1
  • 8
  • 2
    Don't post text as image; post it as text. – Uwe Keim Dec 31 '19 at 13:32
  • 1
    It would surprise me if you succeeded to pass a PyShark object into Scapy without it crashing – Cukic0d Dec 31 '19 at 15:06
  • Welcome to Stack Overflow! Please read the [help pages](https://stackoverflow.com/help), take the [SO tour](https://stackoverflow.com/tour), read about [how to ask good questions](https://stackoverflow.com/help/how-to-ask), as well as this [question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Ross Jacobs Dec 31 '19 at 21:57

1 Answers1

3

Just did exactly what you want:

cap = pyshark.FileCapture('path.pcap', display_filter=filter_str, output_file='path_to_save.pcap')
cap.load_packets()

And this will save packets to 'path_to_save.pcap'

This method will loade captured file to memory. So scapy is not needed.

kazhem
  • 31
  • 1