我试图让 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'
这个目录应该在哪里,我怎样才能运行这个代码?
FileNotFoundError: [Errno 2] 没有这样的文件或目录:'tshark'
这是要注意的重要错误。这意味着“tshark”还没有被 python 找到,这意味着其中一个:
根据
/Library...
错误,您的操作系统似乎是 macOS。
如果您还没有安装 tshark,您可以使用
brew install --cask wireshark
或从 wireshark.org 下载安装程序来安装它。然后,当您在脚本中使用tshark
(并且它在 PATH 上)时,您将不会收到文件未找到的错误。
如果您在终端上运行
which tshark
并且没有得到任何响应,则 tshark 不在您的 PATH 上。要添加它,请将其添加到您的 ~/.profile
文件中(如果使用 zsh,则为~/.zprofile
):
export PATH=/path/to/tshark:$PATH
你可以用 python 在 python 中检查这个
import os
print(os.environ['PATH'])
应该打印出当前的路径。请记住,您可能需要重新启动 shell/终端才能使配置文件更改生效。
您可以通过运行
which tshark
来检查tshark的安装位置。如果 which tshark
返回一个值,您可以在脚本的 Popen 中使用该文件路径代替 'tshark'
。
在我的 Macbook 上,它位于
/Applications/Wireshark.app/Contents/MacOS/tshark
,但它很可能位于您系统上的不同位置。
我认为更好的解决方案是使用
PyShark
,这是一个为处理 tshark 的输出而构建的 python 库。
文档:https://kiminewt.github.io/pyshark/
设置教程:https://tateg.medium.com/capturing-network-traffic-with-python-and-tshark-19599d39dbce