Search code examples
pythonsubprocesspython-3.4tcpdump

Executing the next line of code after subprocess.popen


I am executing Tcpdump command using Popen. In my code, the popen line runs but it does not execute the next line of code following the popen line of code. Why is it happening and how can I solve this ? Thanks.

from subprocess import Popen, PIPE
import os
import time

pw ='12345678'
process = Popen(['sudo', '-S', 'tcpdump', '-i', 'wlp1s0', 'udp', 'port 8308', '-w', 'trace.pcap'], stdout=PIPE,universal_newlines=True,stdin=PIPE)
process.communicate(pw + '\n')[1]
print("Command ran")
time.sleep(3)

Here the "Command ran" is not printed.


Solution

  • process.communicate waits for process to terminate.

    If you want to send input to process without waiting for termination use process.stdin.

    process.stdin.write(password + "\n")
    

    tcpdump will not terminate with your parameters unless you send SIGINT signal.

    Tcpdump will, if not run with the -c flag, continue capturing packets until it is interrupted by a SIGINT signal (generated, for example, by typing your interrupt character, typically control-C) or a SIGTERM signal (typically generated with the kill(1) command); if run with the -c flag, it will capture packets until it is interrupted by a SIGINT or SIGTERM signal or the specified number of packets have been processed.

    You can include -c flag in your parameters.