运行 tcpdump bash 从 python 使用子进程 x 分钟

Run tcpdump bash from python for x minutes using subprocess

我想从 python 运行 tcpdump 用户指定的 x 分钟。目前我的函数如下所示:

def tcpdump():
    run_time = int(input("\nHow many minutes would you like the bash to run?\n"))

    time_to_end = time.time() + 60 * run_time

    print("\ntcpdump running...\n")

    while time.time() < time_to_end:
        p = subprocess.Popen("./tcpdump.bash", shell=True) 
    p.terminate()

然而,当我得到以下输出时,这似乎重复启动了 tcpdump:

tcpdump: (all BPF devices are busy)
tcpdump: (all BPF devices are busy)
tcpdump: (all BPF devices are busy)

我不确定如何解决这个问题,另外我不确定如何终止进程,因为 p.kill() 似乎不起作用。

---------------- 已编辑--------------------

我现在已经尝试了以下方法,但是我不确定我的子进程是否被正确终止,或者它是否会在后台无限地运行:

def tcpdump:
    run_time = int(input("\nHow many minutes would you like to collect benign data?\n"))

    time_to_end = time.time() + 60 * run_time

    print("\ntcpdump running...\n")

    p = subprocess.Popen(['tcpdump', '-i', 'en0', '-w', 'test.pcap']))
    while time.time() < time_to_end:
          p.communicate()
    p.kill()

你已经安排好了时间,但问题是每次 while 循环运行时它都会再次 popen 并产生一个新进程。

宁愿这样做:

import threading
import subprocess

def tcpdump():
    print("\ntcpdump running...\n")
    p = subprocess.Popen("./tcpdump.bash", shell=True)
    p.wait()

run_time = int(input("\nHow many minutes would you like the bash to run?\n"))
t = threading.Thread(target=tcpdump, daemon=True)
t.start()
t.join(run_time * 60)

tcpdump 函数现在只打开一个进程并等待它关闭。主要代码使用指定超时的 Threading.join 函数。一旦超时结束,child 线程将被终止,控制权将返回给父进程。