使用 python 脚本运行 Tshark

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

我试图让 tshark 通过 python 脚本运行并获得回溯 [我正在使用 ptyhon 3.9]

这是我正在使用的 python 脚本:

import subprocess
from pythonosc import osc_message_builder, udp_client # python 3.3.x+

osc = udp_client.UDPClient('localhost', 8000)
popen = subprocess.Popen(['tshark', '-l'], stdout=subprocess.PIPE)
for traffic in iter(popen.stdout.readline, ''):
    traffic = traffic.decode('utf-8').strip()
    #print(traffic)
    msg = osc_message_builder.OscMessageBuilder(address='/tsharky')
    msg.add_arg(traffic, 's')
    msg = msg.build()
    osc.send(msg)

这是我得到的回溯:

Traceback (most recent call last):
  File "/Users/trem/Downloads/tsharky-master/tsharky.py", line 18, in <module>
    popen = subprocess.Popen(['tshark', '-l'], stdout=subprocess.PIPE)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1821, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'tshark'

这个目录应该在哪里,我怎样才能运行这个代码?

python tshark
2个回答
1
投票

错误

FileNotFoundError: [Errno 2] 没有这样的文件或目录:'tshark'

这是要注意的重要错误。这意味着“tshark”还没有被 python 找到,这意味着其中一个:

  1. tshark 没有安装
  2. tshark 已安装,但它不在PATH
  3. tshark安装好了,但是python找不到

根据

/Library...
错误,您的操作系统似乎是 macOS。

1。安装 tshark

如果您还没有安装 tshark,您可以使用

brew install --cask wireshark
或从 wireshark.org 下载安装程序来安装它。然后,当您在脚本中使用
tshark
(并且它在 PATH 上)时,您将不会收到文件未找到的错误。

2。将 tshark 添加到 PATH

如果您在终端上运行

which tshark
并且没有得到任何响应,则 tshark 不在您的 PATH 上。要添加它,请将其添加到您的
~/.profile
文件中(如果使用 zsh,则为
~/.zprofile
):

export PATH=/path/to/tshark:$PATH

你可以用 python 在 python 中检查这个

import os
print(os.environ['PATH'])

应该打印出当前的路径。请记住,您可能需要重新启动 shell/终端才能使配置文件更改生效。

3。在 Popen

中使用 tshark 路径代替“tshark”

您可以通过运行

which tshark
来检查tshark的安装位置。如果
which tshark
返回一个值,您可以在脚本的 Popen 中使用该文件路径代替
'tshark'

在我的 Macbook 上,它位于

/Applications/Wireshark.app/Contents/MacOS/tshark
,但它很可能位于您系统上的不同位置。


0
投票

我认为更好的解决方案是使用

PyShark
,这是一个为处理 tshark 的输出而构建的 python 库。

文档:https://kiminewt.github.io/pyshark/

设置教程:https://tateg.medium.com/capturing-network-traffic-with-python-and-tshark-19599d39dbce

© www.soinside.com 2019 - 2024. All rights reserved.