子进程抛出错误来运行命令

问题描述 投票:0回答:1

我正在尝试编写一个测试用例,其中我下载一个文件(PCAP)文件,然后将其保存为名称 test1.pcap 然后我希望通过

tshark
cli 工具对其进行验证,

"tshark -r {} -Y http".format(filename)
``

its says ```
OSError(2, 'No such file or directory')

但是,当我使用 os.path.exsists(filename) 检查该文件时,该文件存在

我的代码是:

def test_pcap():

.....
   pcap_response = requests.get(pcap_url)
      assert pcap_response.status_code == 200, "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.,")

   with open(pcap_file_path, 'w') 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("tshark -r {} -Y http".format(pcap_file))
        result = subprocess.Popen(
            ["sudo", "tshark", "-r {}".format(pcap_file), "-Y", "http"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        r1, r2 = result.communicate
        print("Next step after result and result is: ", result, r1, r2)
        if result.returncode == 0 and result.stdout:
            print("PCAP file validation passed.")
            print("Output:\n", result.stdout)
            return True
        else:
            print("No matching traffic found or tshark error.")
            print("Error:\n", result.stderr)
            return False
    except Exception as e:
        print("Error running tshark:", e)
        return 
    
python wireshark pcap tshark pcap.net
1个回答
0
投票

一方面,如果您已经有捕获文件,则不需要

sudo
来运行
tshark

我建议使用

shutil.which()
来查找 tshark:

tshark = shutil.which("tshark")
if not tshark:
    raise FileNotFoundError("tshark not found")
cmd = [tshark, "-r", pcap_file, "-Y", "http"]
result = subprocess.Popen(cmd, ...
© www.soinside.com 2019 - 2024. All rights reserved.