连续读取python中连续写入的pcap文件

问题描述

使用 Python 我想从 pcap 连续写入的 tshark 文件中,按照写入数据包的相同顺序连续读取数据包(或用 libpcappfring) 实时捕获编写的一段代码

为了测试这一点,我在 Python 中使用了 tsharkscapy方法如下。

@terminal1:ping -i 5 192.168.1.10

@terminal2:tshark -f "icmp" -a filesize:1000 -w ping_live.pcap

Python 中的数据包阅读器旨在每 5 秒读取每个未读数据包(而不是每次都读取整个数据包)。但它不会等待 5 秒后即将写入的下一组数据包,并退出

from scapy.all import *

def process_packet(packet):
    print(packet.summary())

sniff(offline="ping_live.pcap",prn=process_packet,store=0)
print("sniff complete,exiting")

然后我尝试在 while True: 方法周围放置 sniff 循环,但它不是只读取下一个未读数据包,而是一次又一次地读取整个文件

我的要求有什么解决方案(不限于scapy)?

谢谢

解决方法

我不确定这是否能回答您的问题,因为我无法理解确切的要求。根据我对您问题中信息的解释,您希望“按照写入 PCAP 文件的顺序连续读取数据包。”

您的示例使用了 ICMP, 所以我的回答将使用该协议。

import pyshark

# filter live capture by type,which is ICMP
capture = pyshark.LiveCapture('en0',display_filter='icmp')

for packet in capture:

    # obtain all the field names within the ICMP packets
    field_names = packet.icmp._all_fields

    # obtain all the field values 
    field_values = packet.icmp._all_fields.values()

    # enumerate the field names and field values
    for field_name,field_value in zip(field_names,field_values):

        # filter the time stamp
        if field_name == 'icmp.data_time':
            print(field_value)
            # output
            Mar 21,2021 09:03:21.681450000 EDT
            Mar 21,2021 09:03:22.686135000 EDT
            Mar 21,2021 09:03:23.689576000 EDT
            Mar 21,2021 09:03:24.691429000 EDT
            Mar 21,2021 09:03:25.692395000 EDT
            Mar 21,2021 09:03:25.692395000 EDT
            truncated...

这里是可以过滤的字段名称:

icmp.type
icmp.code
icmp.checksum
icmp.checksum.status
icmp.ident
icmp.seq
icmp.seq_le
icmp.data_time
icmp.data_time_relative
data
data.data
data.len

希望这个答案对您有所帮助。

附言这是我使用 pyshark 编写的 GitHub 文档。