【问题标题】:Python and NGREPPython 和 NGREP
【发布时间】:2010-02-25 16:06:36
【问题描述】:

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

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

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

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

谢谢。

【问题讨论】:

    标签: python process input system ngrep


    【解决方案1】:

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

    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 运行它。

    希望对你有帮助!

    【讨论】:

    • 如果你从不修改keep_running,就不用定义while True:。您的os.system(sudo killall ngrep) 行缺少引号,您应该真的改用subprocess.call
    • 您好 Martijn,对不起,我的语法很笨拙,感谢您的指正!我把'keep_running'放在那里是为了给Dave一个可选行'if run_hours > 100:keep_running=0'的想法。我在 Mac Os 10.4.11 上,我有 Python 2.3.5,所以我认为我无法访问 subprocess 模块。
    • 我希望我至少能得到 2.6。 :)
    • 如果设置shell=True,则无需传入列表,而在第二个subprocess.call中,则无需使用shell=True,因为您没有重定向输出。
    【解决方案2】:

    它不是内置的,但你可以试试Packet Capture and Injection Library

    【讨论】:

      【解决方案3】:

      查找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
      

      EDIT2:如果您想手动进行数据包捕获,请使用pypcap。这几乎肯定可以满足您的需求,因为 tcpdump 使用 libpcap 本身。

      【讨论】:

      • 我不确定为什么 threading.Timer 在这种情况下会有用。
      • 因为他想每小时运行一次...所以,创建一个threading.Timer(3600, runNgrep, args, kwargs) 来运行程序并在程序完成时创建另一个threading.Timer... 其中runNgrep 是一个函数显然,将 argskwargs 作为参数。
      • 这些都是很好的建议。知道如何杀死该进程吗?我看到了文档。似乎 send_signal()、terminate() 和 exit() 方法仅在 python 2.6 中可用我正在运行 python 2.5。按照您的建议,我使用 subprocess.Popen 然后获取进程 ID,然后使用 kill pid 运行 subprocess.Popen 来编辑进程。不太优雅,也许有更好的方法来终止进程?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多