Python and NGREP
I want to be able to start and stop an NGREP process from inside my python code. I really dont have experience with python on a system level.
Normally I run NGREP from the command line, but I would like to be able to run it from a script every hour and capture the trace and then process the results.
Can anyone point me in the direction of how to achieve this.
By the way, I really just need to be able to do a packet c开发者_Python百科apture, perhaps Python has builtin capabilities for this, maybe tcpdump?
Thanks.
I am not an expert but I would do this:
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
You will have to run it as root or with sudo.
I hope it helps!
its not in-built, but you can try Packet Capture and Injection Library
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.
精彩评论