Running Tshark with a python script

Viewed 913

I'm trying to get tshark running through a python script and get a traceback [and I'm using ptyhon 3.9]

This is the python script which I'm using:

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)

This is the traceback that I get:

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'

Where should this directory be and how can I get this code running?

1 Answers

Error

FileNotFoundError: [Errno 2] No such file or directory: 'tshark'

This is the important error to look at. It means that 'tshark' has not been found by python, meaning one of a couple of things:

  1. tshark is not installed
  2. tshark is installed, but it's not in PATH
  3. tshark is installed, but python can't find it

It looks like your OS is macOS based on the /Library... error.

1. Install tshark

If you haven't installed tshark, you can install it with brew install --cask wireshark or by downloading the installer from wireshark.org. Then, when you use tshark in scripts (and it's on the PATH), you won't get a file-not-found error.

2. Add tshark to PATH

If you run which tshark on your terminal and get no response, tshark is not on your PATH. To add it, add this to your ~/.profile file (~/.zprofile if using zsh):

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

You can check this in python with

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

which should print out the current PATH. Keep in mind that you may need to restart your shell/terminal for your profile changes to take effect.

3. Use the tshark path in place of 'tshark' in Popen

You can check where tshark is installed by running which tshark. If which tshark returns a value, you can use that filepath in place of 'tshark' in Popen in your script.

On my Macbook, it's located at /Applications/Wireshark.app/Contents/MacOS/tshark, but it may well be in a different place on your system.

Related