You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求指导:用Python生成串口数据的Wireshark/pcap兼容跟踪文件

串口转PCAP解决方案与格式说明

一、PCAP格式选择

针对你的场景,核心逻辑如下:

  • 若串口数据是自定义逻辑打包的,无需强制套SLIP/PPP封装,直接用原始串口数据格式即可。PCAP支持封装任意原始帧,对应Wireshark的链路层类型DLT_RAW(数值101),Wireshark可直接解析这类文件。
  • 仅当你的串口数据本身就是SLIP/PPP协议传输的(比如早期拨号链路场景),才需要用DLT_SLIP或DLT_PPP格式封装,否则只会增加解析复杂度。

二、Python实现方案

推荐用轻量库组合快速实现:

1. 核心依赖

  • pyserial:负责串口数据读取,支持波特率、奇偶校验等全配置。
  • scapy/dpkt:生成PCAP文件,前者易用性高适合快速开发,后者轻量性能优适合高吞吐量场景。

Scapy示例代码

import serial
from scapy.all import wrpcap, Raw

# 串口配置,替换为你的实际参数
ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
)

captured_frames = []

try:
    while True:
        # 按你的打包规则读取一帧数据,示例为按NULL字节分隔,需自行替换
        frame = ser.read_until(b'\x00')
        if frame:
            # 封装为Raw数据包,链路层类型默认对应DLT_RAW
            pkt = Raw(load=frame)
            captured_frames.append(pkt)
            # 批量写入避免频繁IO
            if len(captured_frames) >= 100:
                wrpcap('serial_capture.pcap', captured_frames, append=True)
                captured_frames = []
except KeyboardInterrupt:
    # 退出时写入剩余数据
    if captured_frames:
        wrpcap('serial_capture.pcap', captured_frames, append=True)
    ser.close()
    print("捕获结束,文件已保存为serial_capture.pcap")

dpkt示例代码

import serial
import dpkt
import time

# 串口配置
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

# 打开PCAP文件,指定链路层类型为DLT_RAW
with open('serial_capture.pcap', 'wb') as f:
    pcap_writer = dpkt.pcap.Writer(f, linktype=dpkt.pcap.DLT_RAW)
    try:
        while True:
            frame = ser.read_until(b'\x00')  # 替换为你的帧结束规则
            if frame:
                # 生成时间戳(秒+微秒)
                ts = time.time()
                pcap_writer.writepkt(frame, ts=(int(ts), int((ts - int(ts)) * 1e6)))
    except KeyboardInterrupt:
        ser.close()
        print("捕获结束,文件已保存为serial_capture.pcap")

三、Wireshark解析提示

生成的PCAP文件直接打开即可,Wireshark会把每个帧识别为原始数据。如果你的打包数据有自定义协议,可通过**「分析 -> 解码为...」**指定对应解析规则,或编写自定义Lua插件实现深度解析。


内容的提问来源于stack exchange,提问作者Paul D Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:15:33