Tuesday, June 11, 2013

Windows Process Monitor Script in Python

I have a windows desktop that is always tunneled to some server for reason that is not important. I use kitty.exe an improved putty with auto re-login and more, but only needed that feature that's why I'm using that. But for some reason it stops responding if a lot of traffic has passed to the tunnel and it has now happened too frequent that I just had to auto restart it, there might be softwares that does this already but here is what I did using python. This should be reusable with any process just change the variable names you want to monitor.

import os
import subprocess
import time

__author__ = 'faisal'

# Change this if you want to monitor a different process
process_name = 'kitty.exe'
# Separate your parameters
start_command = ['C:\Applications\Putty\kitty.exe', '-load', 'MyTunnelSession']
# Sleep time in seconds before checking again
sleep_time = 60

while True:
    # Filter a list of windows process that has stopped responding
    r = os.popen('tasklist /FI "STATUS eq Not Responding"').read().strip().split('\n')
    for p in r:
        if p.startswith(process_name):
            # It's a quick script so just go get the
            # first # valid info which is the PID
            d = p.split(' ')
            i = d.pop(0)
            while not i:
                i = d.pop(0)
            # Kill by PID
            k = os.popen('taskkill /F /T /PID %s' % i).read()
            print k

    # Now we check if kitty.exe is running then run it if its not loaded
    r = os.popen('tasklist /FI "STATUS eq Running"').read().strip().split('\n')
    found = False
    for p in r:
        if p.startswith(process_name):
            found = True

    if not found:
        with open(os.devnull, 'wb') as devnull:
            subprocess.Popen(start_command, stdout=devnull, stderr=subprocess.STDOUT)

    print 'Running time: %s' % time.time()

Also let this start your process instead of having it already started.