Python与NGREP

0 投票
3 回答
1150 浏览
提问于 2025-04-15 19:43

我想在我的Python代码里启动和停止一个NGREP进程。老实说,我对Python在系统层面的使用经验不多。

通常我是在命令行里运行NGREP,但我希望能通过脚本每小时运行一次它,捕获数据包,然后处理结果。

有没有人能告诉我怎么做到这一点?

顺便说一下,我其实只需要做数据包捕获,可能Python本身就有这个功能,或者可以用tcpdump?

谢谢。

3 个回答

0

这个功能不是内置的,但你可以试试这个叫做 Packet Capture and Injection Library 的库。

0

你可以查一下 threading.Timerpexpect。如果你不想安装 pexpect,可以用 subprocess.Popen 来代替。

编辑:针对评论的回复:

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

编辑2:如果你想自己实现数据包捕获,可以使用 pypcap。这应该能满足你的需求,因为 tcpdump 本身就是用 libpcap 的。

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

你需要以管理员身份运行这个,或者用sudo命令来执行。

希望这能帮到你!

撰写回答