0

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

2
  • 1
    You have to pass one argument per item, and no quotes. check_output() is not a shell (unless you pass shell=True, but this is not necessary in your case) Commented Mar 21, 2016 at 9:53
  • so what should I do? I read in another post that I should avoid the using of shell = True Commented Mar 21, 2016 at 10:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried to wrote: p = subprocess.Popen(('sudo', 'tcpdump', '-n', '(dst port 515 or dst port 9100)'), stdout=subprocess.PIPE) for row in iter(p.stdout.readline, b''): print row.rstrip() and I don't get anything, when I run the same command in terminal I get all the traffic
@azDev: it may be because of buffering. Try using -l

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.