0

我希望能够从我的 python 代码中启动和停止 NGREP 进程。我真的没有系统级别的python经验。

通常我从命令行运行 NGREP,但我希望能够每小时从脚本运行它并捕获跟踪然后处理结果。

谁能指出我如何实现这一目标的方向。

顺便说一句,我真的只需要能够进行数据包捕获,也许 Python 已经为此提供了内置功能,也许是 tcpdump?

谢谢。

4

3 回答 3

2

我不是专家,但我会这样做:

import subprocess
import sys
import re
import time

keep_running = 1 #Loop flag
wait_hours = 12  #Stop for 12 hours and then run again
run_hours = 1    #We will run ngrep for an hour. The nth run will be dumped to net_log_n.txt
f_num=0
hours_so_far=0
run_time_limit = 100    #Suppose you only want to take a log for 100 hours while you are away.
while keep_running:
    ngrep_cmd = "sudo ngrep -ixW >  net_log_" + str(fnum) + ".txt &"
    subprocess.call([ngrep_cmd], shell=True)
    time.sleep(run_hours*3600)
    subprocess.call(["sudo killall ngrep"], shell=True)
    time.sleep(wait_hours*3600)
    f_num += 1
    hours_so_far += run_hours
    if hours_so_far >= run_time_limit:
        keep_running = 0

您必须以 root 身份或使用 sudo 运行它。

我希望它有帮助!

于 2012-10-29T08:11:10.113 回答
0

Look up threading.Timer and pexpect. If you don't want to install pexpect, you can use subprocess.Popen instead.

EDIT: In response to the comment:

import os
from signal import SIGTERM, SIGKILL
os.kill(pid, SIGTERM) #you can also send SIGKILL instead of SIGTERM. 
#You might also have to put this call in a try block and catch OSError
#Only available on *NIX

EDIT2: If you want to hand-roll the packet capture, use pypcap. This should almost certainly do what you want, since tcpdump uses libpcap itself.

于 2010-02-25T16:17:09.183 回答
0

它不是内置的,但您可以尝试数据包捕获和注入库

于 2010-02-25T16:45:23.020 回答