python在给定时期启动和停止tcpdump命令

时间:2018-10-25 13:12:22

标签: python subprocess scheduler

tcpdump在两个给定的时期内每1分钟生成一次pcap,例如从今天的午夜到明天的午夜开始生成数据包。当python脚本在预定的时间段启动它时,它会这样做。我希望它像tcpdump ... &这样在后台运行,但是sudo python3 capture.py会产生:pktap_filter_packet: pcap_add_if_info(lo0, 0) failed: pcap_add_if_info: pcap_compile_nopcap() failed. 另一个问题是我希望在python中保存p.pid,并在另一个预定的时期杀死pid。 `

import os, time
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import subprocess
import shlex

def start_catch():
    shell_cmd = 'tcpdump -i any -G 60 -w packets-%Y-%m-%d_%H.%M.%S.pcap &' # this & causes problem but without it the tcpdump blocks the progress
    cmd = shlex.split(shell_cmd)
    p = subprocess.Popen(cmd, shell=False)
    if p.returncode == 0:
        print('Subprogram success')
    else:
        print('Subprogram failed')

scheduler = BackgroundScheduler()
dd = datetime.now() + timedelta(seconds=10)
job = scheduler.add_job(start_catch, 'date',run_date=dd, args=[])

try:
    scheduler.start()
except Exception as e:
    print(e)
    scheduler.shutdown()

# continue to do other things.

0 个答案:

没有答案