如何使用Scapypcapwriter在FIFO中写入Pcap数据包

问题描述

我是法国人,如果我的英语不完美,很抱歉!
开始之前,如果您想尝试我的代码,可以在这里下载一个pcap示例文件https://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=ipv4frags.pcap

我成功打开了pcap文件,读取了数据包,并使用以下代码将其写入另一个文件

# Python 3.6
# Scapy 2.4.3

from scapy.utils import PcapReader,PcapWriter
import time

i_pcap_filepath = "inputfile.pcap"  # pcap to read
o_filepath = "outputfile.pcap"  # pcap to write


i_open_file = PcapReader(i_pcap_filepath)  # opened file to read
o_open_file = PcapWriter(o_filepath,append=True)  # opened file to write

while 1:
    # I will have EOF exception but anyway
    time.sleep(1)  # in order to see packet
    packet = i_open_file.read_packet()  # read a packet in file
    o_open_file.write(packet)  # write it

所以现在我要写一个FIFO,并在实时的Wireshark窗口中查看结果。
为此,我只需创建一个FIFO: $ mkfifo /my/project/location/fifo.fifo
并在其上启动Wireshark应用程序:$ wireshark -k -i /my/project/location/fifo.fifo
我在Python脚本中更改了文件路径:o_filepath = "fifo.fifo" # fifo to write

但是我崩溃了……这是回溯:

Traceback (most recent call last):
  File "fifo.py",line 25,in <module>
    o_open_file = PcapWriter(o_pcap_filepath,append=True)
  File "/home/localuser/.local/lib/python3.6/site-packages/scapy/utils.py",line 1264,in __init__
    self.f = [open,gzip.open][gz](filename,append and "ab" or "wb",gz and 9 or bufsz)  # noqa: E501
OSError: [Errno 29] Illegal seek

Wireshark也给我一个错误(“打开期间管道魔术文件的结尾”):wireshark error

我不明白为什么以及该怎么做。使用scapy.utils库无法写入FIFO吗?那怎么办?

感谢您的支持
Nicos44k

解决方法


晚上非常有用,因为我今天早上解决了问题!

昨天我并没有理解追溯,但实际上给了我一个很大的提示:我们有一个寻找问题。
等等... FIFO文件中没有寻找!!!

因此,我们无法将“ append”参数设置为true。
我更改为:o_open_file = PcapWriter(o_filepath)
错误消失了。

但是,数据包没有实时显示...
要解决此问题,我需要使用以下命令强制FIFO刷新:o_open_file.flush()

请记住,您可以在此处下载pcap示例文件:https://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=ipv4frags.pcap
这是完整的代码:

# Python 3.6
# Scapy 2.4.3

from scapy.utils import PcapReader,PcapWriter
import time

i_pcap_filepath = "inputfile.pcap"  # pcap to read
o_filepath = "fifo.fifo"  # pcap to write

i_open_file = PcapReader(i_pcap_filepath)  # opened file to read
o_open_file = PcapWriter(o_filepath)  # opened file to write

while 1:
    # I will have EOF exception but anyway
    time.sleep(1)  # in order to see packet
    packet = i_open_file.read_packet()  # read a packet in file
    o_open_file.write(packet)  # write it
    o_open_file.flush()  # force buffered data to be written to the file

祝你有美好的一天!
Nicos44k