soln.py [download]
#!/usr/bin/python
'''This program is designed to be run as a cron job.
It will check if a process is running on a remote machine.
The input file should look like:
host:process
'''
import sys, subprocess, smtplib
ADMIN_EMAIL = 'theemailaddressyouwantmesagesdeliveredto@foo.com'
def usage():
print('Usage: ./process_monitor.py hostlist')
def check(HOST, process):
COMMAND = "ps aux | grep " + process
COMMAND = "service "+process+" status | egrep 'Active' | awk '{ print $2}'"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
#print (result)
return result[0].rstrip()
def process_result(result, process ):
if result == 'active':
print (process + " is active. Doing nothing.")
return 1
else:
print (process + " is not running, sending Alert")
return 0
def send_alert(process, machine):
#this will only work if you are sending from one of your campus vm's
server = smtplib.SMTP('stumail.cs.utahtech.edu', 25)
server.ehlo()
msg = "This is an alert"
#sender address listed first, can be fake
#GMAIL DOESN"T LIKE THIS, but it works until they blacklist us ;-)
server.sendmail("fakedude@nowehere.com", ADMIN_EMAIL, msg)
server.quit()
def main():
#loop through the input file
if (len(sys.argv) != 2):
usage()
exit()
filename = sys.argv[-1]
print("Reading from " + filename)
msg = ''
try:
f = open(filename)
for line in f:
line = line.strip()
line = line.split(':')
m = line[0]
process = line[1]
print ("Checking for " + process + " on machine " + m)
result = check(m, process)
err = process_result(result, process)
if err == 0:
send_alert(process, m)
except Exception as e:
print (e)
main()
Last Updated 02/07/2025