Tuesday, May 12, 2009

Cron on Linux

If you have many scripts running on a server machine(I have 6 scripts running on different machines). These scripts can be monitoring script or something important to the system. But sometime these script can crash due to some unknown reasons. At this time it's very dangerous to the system. So setting up one mechanism to monitor the condition of these scripts is very important to the system and your work. The CRON job can do this job. CRON is part of Linux and can be used to run a script at some time you want. You can use this to open the cron job setting.

crontab -e
Add this to this file.

*/5 * * * * /usr/local/bin/mcJobMonitor.py >> /dev/null

If you want to know the meaning of this sentence, please go to Cron on Linux.
This mcJobMonitor.py is
#!/usr/bin/python
#//////////////////////////////////////////////////
# Haifeng Li
#///////////////////////////////////////////////////

import sys, os, time, commands, getopt

def SendMailtoUser(ScriptName ):

hostname = commands.getoutput("uname -n")
timedate = commands.getoutput("date")
pwd = commands.getoutput("pwd")
message = "Your script "+ScriptName+" in machine " +hostname+ " is dead. \n"\
+"We have restarted this script. You can go to this machine to check the reason. \n"
email = "xxxxxxx@gmail.com"
command ="".join(["echo \"", message, \
"\" | mail ", email, " -s \"Cron Monitor for ", ScriptName, "\""])
os.system(command)

if __name__=="__main__" :

#________________________updatedatabase.py________________________________
ScriptName = "/var/www/html/hpeng3/script/updatedatabase.py"
status = commands.getoutput("ps -ef | grep 'updatedatabase.py' | grep -v grep")
status = status.strip()
if status == '' :
pushd = "pushd /var/www/html/hpeng3/script"
restart = "./restart.sh"
popd = "popd"
command = ";".join([pushd, restart, popd])
os.system(command)
SendMailtoUser(ScriptName )

Monday, May 4, 2009