1

我有一个程序可以使用 pyshark.FileCapture 扫描 pcap 文件,然后打印过滤后的数据包。

我想将这些数据包保存到一个新的 pcap 文件中。

代码:

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()

我尝试使用 scapy,但 save_to_pcap() 函数不起作用,并且弹出此异常:

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'
4

1 回答 1

2

只是做了你想要的:

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

这会将数据包保存到“path_to_save.pcap”

此方法会将捕获的文件加载到内存中。所以不需要scapy。

于 2020-01-28T21:51:16.897 回答