views:

98

answers:

2

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 capture, perhaps Python has builtin capabilities for this, maybe tcpdump?

Thanks.

A: 

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.

Chinmay Kanchi
I'm not sure why a threading.Timer would be useful in this case.
nosklo
Because he wants to run it every hour... So, create a `threading.Timer(3600, runNgrep, args, kwargs)` to run the program and create another `threading.Timer` when the program finishes... Where `runNgrep` is a function taking `args` and `kwargs` as arguments, obviously.
Chinmay Kanchi
These are good suggestions. Any idea how to kill the process though? I see the docs. it seems like send_signal(), terminate() and exit() methods are only available in python 2.6 I am running python 2.5. Following your suggestion, I use subprocess.Popen then get the process id and then run subprocess.Popen with a kill pid to ed the process. Not so elegant, perhaps there is a better way to terminate the process?
Dave
A: 

its not in-built, but you can try Packet Capture and Injection Library

ghostdog74