【问题标题】:Using subprocess to call a tshark command使用子进程调用 tshark 命令
【发布时间】:2020-10-20 18:10:27
【问题描述】:

我正在尝试使用以下命令在 Python 中读取 .pcapng

tshark_out = subprocess.getoutput('tshark -r USB.pcapng')

但是,我的代码会产生错误

UnicodeDecodeError:“ascii”编解码器无法解码位置 30 中的字节 0xe2:序数不在范围内 (128)

我可以通过在我的命令中进行转换来解决这个问题,还是需要通过更改我的 Python 脚本来解决这个问题?

【问题讨论】:

    标签: python python-3.x wireshark tshark


    【解决方案1】:

    您在 Python3 中使用旧版 Python2 子命令(请参阅 subprocess.getoutput docs

    部分问题是您正在使用 getoutput 将字节对象隐式转换为字符串。 0xe2 是 226,大于 ASCII 的 128 范围。 相反,您应该将 stdout 和 stderr 作为字节对象获取并在稍后的命令中进行转换。例如:

    # captures the output for 1 packet.
    import subprocess as sp
    cmd = sp.run(["tshark", "-c", "1"], stdout=sp.PIPE, stderr=sp.PIPE)
    print("STDOUT:\n", cmd.stdout, "\n\nSTDERR:\n", cmd.stderr)
    

    给出输出

    STDOUT:
    b'    1   0.000000 179.118.244.35.bc.googleusercontent.com \xe2\x86\x92 
    192.198.128.5 TLSv1.2  105 Application Data 6c:94:cf:d8:7f:e7 \xe2\x86\x90 
    e0:55:3d:71:f7:29\n' 
    
    STDERR:
    b"Capturing on 'Wi-Fi: en0'\n1 packets dropped from Wi-Fi: en0\n1 packets captured\n"
    

    您现在有了用于 stdout 和 stderr 的字节对象。您可以使用任何您想要的编码(如 ASCII、UTF-8)对它们进行解码,或者在您的代码中使用它们。

    您可能还想查看scapy,这是一个用于处理数据包的python库。

    注意:这个例子使用了run,但是有很多Python Popen wrappers做类似的事情。

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2015-01-13
      • 2014-11-15
      • 2021-04-11
      • 2019-01-08
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 2012-03-19
      相关资源
      最近更新 更多