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

Python调用tshark导出JSON文件需手动中断才能完成完整写入

问题分析

你遇到的核心问题是:tshark在以-T json模式输出结果时,会将所有匹配条目封装为一个JSON数组,这意味着它需要处理完所有符合条件的数据包后才会输出数组的闭合括号]。同时,tshark默认使用全缓冲模式输出到文件,未填满缓冲或进程未结束时,内容不会实时写入文件。这就导致:

  1. 进程未终止时,文件缺少数组结尾,触发JSON格式错误
  2. 只有强制终止进程,缓冲内的所有内容才会被flush到文件,你才能看到最后几行数据
解决方案

方案1:改用jsonraw输出格式

tshark的-T jsonraw选项会为每个匹配数据包输出独立的JSON对象(每行一个),处理一个包就输出一行,内容实时写入文件,无需等待所有包处理完成,也不会出现数组不闭合的问题。

修改后的代码:

file_name = "my_file.pcap"
output_file = 'output_json.json'

start_time = datetime.datetime(2023, 3, 24, 11, 57, 39)
end_time = datetime.datetime(2023, 3, 24, 11, 57, 40)

command = [
        "tshark", "-r", file_name, "-Y",
        f'(oran_fh_cus.extType == 11) && (frame.time >= "{start_time.strftime("%Y-%m-%d %H:%M:%S")}" && frame.time <= "{end_time.strftime("%Y-%m-%d %H:%M:%S")}")',
        "-T", "jsonraw",  # 替换为jsonraw格式
        "-e", "frame.time", "-e", "frame.number", "-e", "oran_fh_cus.extType",
        "-e", "oran_fh_cus.bfwI", "-e", "oran_fh_cus.bfwQ"
    ]

with open(output_file, "w") as f:
    subprocess.run(command, stdout=f)

如果需要标准JSON数组格式,可以后续用Python处理:

import json

# 将jsonraw输出转为标准JSON数组
with open(output_file, 'r') as f_in, open('final_output.json', 'w') as f_out:
    entries = [json.loads(line) for line in f_in if line.strip()]
    json.dump(entries, f_out, indent=2)

方案2:强制tshark使用行缓冲

用stdbuf命令修改tshark的输出缓冲行为,强制使用行缓冲,确保每输出一行就刷新到文件,同时保留原有的JSON数组格式。

修改后的代码:

file_name = "my_file.pcap"
output_file = 'output_json.json'

start_time = datetime.datetime(2023, 3, 24, 11, 57, 39)
end_time = datetime.datetime(2023, 3, 24, 11, 57, 40)

command = [
        "stdbuf", "-oL",  # 强制stdout使用行缓冲
        "tshark", "-r", file_name, "-Y",
        f'(oran_fh_cus.extType == 11) && (frame.time >= "{start_time.strftime("%Y-%m-%d %H:%M:%S")}" && frame.time <= "{end_time.strftime("%Y-%m-%d %H:%M:%S")}")',
        "-T", "json",
        "-e", "frame.time", "-e", "frame.number", "-e", "oran_fh_cus.extType",
        "-e", "oran_fh_cus.bfwI", "-e", "oran_fh_cus.bfwQ"
    ]

with open(output_file, "w") as f:
    subprocess.run(command, stdout=f)

方案3:排查tshark卡住原因

如果以上方法无效,可能是tshark处理pcap文件时出现异常:

  • 直接运行tshark -r my_file.pcap,检查pcap文件是否损坏
  • 简化过滤条件(比如先去掉时间范围),验证是否是过滤规则导致的卡住
  • 更新tshark到最新版本,旧版本可能存在特定场景的处理bug

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:42:21