Search code examples
pythonsubprocesstcpdump

How to run tcpdump with 2 parameters in as subprocess in python and how to get its output?


I want to run tcpdump with parameters: -n "(dst port 515 or dst port 9100)" -w capture.cap

when I try to do:

dump = subprocess.check_output(["tcpdump",'-n "(dst port 515 or dst port 9100)" -w capture.cap'])

I get exception:

subprocess.CalledProcessError: Command '['tcpdump', '-n "(dst port 515 or dst port 9100)" -w capture.cap']' returned non-zero exit status 1

With 1 parameter it works. Another question is how can I get the output of this command, because it seems to run non-stop.

this code doesn't work as well :

p = subprocess.Popen(('sudo', 'tcpdump', '-l -n "(dst port 515 or dst port 9100)"'), stdout=subprocess.PIPE)
for row in iter(p.stdout.readline, b''):
print row.rstrip()   # process here

Thanks


Solution

  • You have to pass one argument per item, and no quotes:

    subprocess.check_output(['tcpdump', '-n', '(dst port 515 or dst port 9100)', '-w', 'capture.cap'])
    

    check_output() is not a shell (unless you pass shell=True, but this is not necessary in your case): it won't split the arguments for you, and won't interpret quoted strings for you.

    Be sure to read the documentation for subprocess.run() and check the examples.

    By the way, other than the CalledProcessError exception, you should have received this error too:

    tcpdump: invalid option -- ' '
    

    That's an helpful hint: it's complaining about the space after -n.