Python with tcpdump in a subprocess: how to properly close a subprocess?

I have a Python script to capture network traffic using tcpdumpin subprocess:

p = subprocess.Popen(['tcpdump', '-I', '-i', 'en1',
                  '-w', 'cap.pcap'], stdout=subprocess.PIPE)
time.sleep(10)
p.kill()

When this script finishes its work, I try to open the output file .pcapin Wireshark and get this error:

"It looks like the capture file has been cut off in the middle of the package."

What solution can be applied for a “correct” closure subprocess tcpdump?

+4
source share
3 answers

Instead, p.kill()you can use p.send_signal(subprocess.signal.SIGTERM)termination to send the signal, not kill ( p.terminate()does the same).

send_signal() send_signal(). , dir (subprocess.signal) , , .

+3

:
p.kill() p.terminate().
subprocess "" ( tcpdump , ) .pcap .

+2

subprocess. , , https://stackoverflow.com/users/3583715/rkh. :

:

output = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
message = output.stdout.read()
output.stdout.close()

Popen:

output = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
message = output.stdout.read()
output.TerminateProcess()

- , output.kill(), / output.terminate() output.send_signal(subprocess.signal.SIGTERM) , output.TerminateProcess() .

0

Source: https://habr.com/ru/post/1658250/


All Articles