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

调用tshark验证PCAP文件时触发OSError(2)错误求助

问题解决:tshark提示文件不存在但实际文件存在的错误

问题背景

编写测试用例时,先下载PCAP文件保存为test1.pcap,执行tshark -r {} -Y http.format(filename)命令验证,触发OSError(2, 'No such file or directory'),但通过os.path.exists(filename)确认文件确实存在。

错误原因分析

  1. subprocess参数格式错误:调用subprocess.Popen时,将-r {}合并成了单个参数,tshark会把-r test1.pcap当作一个完整的选项名,而非-r选项加文件名参数,导致tshark无法识别该选项,进而抛出文件不存在的错误。
  2. PCAP文件写入模式错误:用文本模式'w'写入二进制PCAP文件,会损坏文件内容,tshark无法正确解析该文件,也可能触发类似文件不存在的异常。
  3. communicate方法调用错误:result.communicate未加括号,没有执行该方法,无法获取命令输出、错误信息,也无法等待命令执行完成。

修复方案

  • 拆分subprocess参数:将"-r {}".format(pcap_file)拆分为"-r", pcap_file两个独立元素,确保tshark正确识别选项和参数。
  • 使用二进制模式保存PCAP:打开文件时用'wb'模式,避免二进制内容损坏。
  • 正确调用communicate方法:添加括号result.communicate(),获取命令执行结果。
  • 可选:如果不需要sudo权限执行tshark,移除sudo,避免不必要的权限问题。

修正后的代码

import os
import requests
import subprocess

def test_pcap():
    # 假设pcap_url和pcap_file_path已提前定义
    pcap_response = requests.get(pcap_url)
    assert pcap_response.status_code == 200, f"Failed to retrieve PCAP file. Status code: {pcap_response.status_code}"
    assert len(pcap_response.content) > 0, "PCAP file is empty"
    print(pcap_response)
    print("PCAP file successfully retrieved.")

    # 二进制模式写入PCAP文件,避免内容损坏
    with open(pcap_file_path, 'wb') as f:
        f.write(pcap_response.content)

    if pcap_file_path is None:
        raise ValueError("PCAP file path is None")

    if not os.path.exists(pcap_file_path):
        print("PCAP file does not exist")
   
    isValid = validate_pcap(pcap_file_path)
    print("pcap validation result is: ", isValid)
    # process_pcap(pcap_file_path)  # 假设该函数已实现
    assert isValid, "Sanitized PCAP file still contains sensitive information."

def validate_pcap(pcap_file):
    if not os.path.exists(pcap_file):
        print("File does not exist.", pcap_file)
        return False
    try:
        print(f"tshark -r {pcap_file} -Y http")
        # 修正参数格式,拆分选项与参数
        result = subprocess.Popen(
            ["tshark", "-r", pcap_file, "-Y", "http"],  # 需要sudo则改为["sudo", "tshark", "-r", pcap_file, "-Y", "http"]
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        # 调用communicate()获取输出和错误
        stdout, stderr = result.communicate()
        print("Command return code:", result.returncode)
        print("Output:\n", stdout)
        print("Error:\n", stderr)
        if result.returncode == 0 and stdout:
            print("PCAP file validation passed.")
            return True
        else:
            print("No matching traffic found or tshark error.")
            return False
    except Exception as e:
        print("Error running tshark:", e)
        return False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:12:05