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

如何使用Python将pcap文件保存为K12文本文件

用Python实现将pcap文件转为Wireshark K12格式文本文件

优先方案:调用Wireshark的tshark命令行工具

Wireshark自带的tshark工具和图形界面使用同一套解析逻辑,能精准导出和手动操作一致的K12格式文本,这是最可靠的实现方式。

实现步骤:

  1. 确保系统已安装Wireshark,且tshark在系统PATH中(若不在,需使用完整路径调用,比如Windows下的C:\Program Files\Wireshark\tshark.exe)。
  2. 使用Python的subprocess模块执行tshark导出命令。

示例代码:

import subprocess

def pcap_to_k12(pcap_file, output_file):
    # 构造tshark命令:读取pcap文件,指定K12格式输出
    cmd = [
        'tshark',
        '-r', pcap_file,
        '-T', 'k12',
        '-w', output_file
    ]
    try:
        # 执行命令,捕获输出用于排查问题
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        print(f"转换完成:{output_file}")
    except subprocess.CalledProcessError as e:
        print(f"转换失败,错误信息:{e.stderr}")

# 调用示例
pcap_to_k12('a.pcap', 'a_k12.txt')

替代方案:用Scapy手动模拟K12格式(不推荐)

若环境限制无法使用tshark,可通过Scapy解析pcap包后手动拼接K12格式内容,但需自行匹配Wireshark导出的格式细节,容易出现偏差。

示例代码(仅做参考,需按需调整格式):

from scapy.all import rdpcap

def scapy_to_k12(pcap_file, output_file):
    packets = rdpcap(pcap_file)
    with open(output_file, 'w', encoding='utf-8') as f:
        for frame_num, pkt in enumerate(packets, 1):
            # 模拟K12格式的帧头部(需对照Wireshark导出内容调整)
            f.write(f"Frame {frame_num}: {len(pkt)} bytes on wire ({len(pkt)*8} bits)\n")
            # 写入以太网层信息
            if pkt.haslayer('Ether'):
                ether = pkt['Ether']
                f.write(f"Ethernet II, Src: {ether.src}, Dst: {ether.dst}\n")
            # 写入IP层信息
            if pkt.haslayer('IP'):
                ip = pkt['IP']
                f.write(f"Internet Protocol Version 4, Src: {ip.src}, Dst: {ip.dst}\n")
            # 按需添加TCP/UDP等其他层的格式内容
            f.write("\n")
    print(f"文件已生成:{output_file}")

# 调用示例
scapy_to_k12('a.pcap', 'a_k12_scapy.txt')

注意:此方案需要逐行匹配Wireshark K12格式的输出规则,适配成本较高,仅在无法使用tshark时考虑。

内容的提问来源于stack exchange,提问作者xiaoxiaojie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:48:57