UNIX Process Time Bomb

Here’s a simple script that kills a process if it lives longer than the time specified. It’s written in Python, and is available on github.

Usage : timebomb.py <process-name> <minutes>

Example : $ timebomb.py firefox-bin 20

Outcome : This will kill the process named firefox-bin if it has been running longer than 20 minutes.

Crontab : You should probably add this to your crontab!

Dependency : Standard UNIX tools : Python 2.4.x, pgrep, ps, kill etc.

# A Pythonic Time Bomb
# Kills Processes Living Longer than the specified time.
# Don't Forget to add it to your crontab!
# http://github.com/eaydin

import subprocess, sys
if len(sys.argv) != 3 :
    print "Usage : timebomb.py <process-name> <time-in-minutes>"
    print "Takes only and exactly 2 arguments."
    raise SystemExit
try : int(sys.argv[2])
except :
    print "%s is not an integer." % sys.argv[2]
    raise SystemExit
try :
    if a == '' :
        raise SystemExit
    else :
        procc = subprocess.Popen(["ps -o pid,bsdtime -p $(pgrep %s)"%(sys.argv)[1]],shell=True,stdout=subprocess.PIPE).communicate()[0]
except : raise SystemExit 
for lines in procc.split('\n') :
    if lines != '' :
        if l[0] == 'PID' : pass
        else :
            if int(l[1].split(':')[0]) >= int(sys.argv[2]) :
                try : killer = subprocess.Popen(["kill","-9",l[0]],stdout=subprocess.PIPE).communicate()[0]
                except : pass
            else : pass

Leave a Reply

Your email address will not be published. Required fields are marked *