I have this python script to check services like MySQL and Apache and if some of them are down then it starts again:
import subprocess
import smtplib
_process = ['mysql', 'apache2']
for _proc in _process:
p = subprocess.Popen(["service", _proc, "status"], stdout=subprocess.PIPE)
output, err = p.communicate()
print "*** check service "+_proc+" ***\n"
if 'Active: active (running)' in output:
print _proc+" is working!"
else:
print "Ouchh!! "+_proc+" again is down."
output = subprocess.Popen(["service", _proc, "start"])
print "*** The service "+_proc+" was restarted ***\n", output
print "*** sending email ***\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
_from = "from@email.co"
_to = "to@email.co"
_cc = ["another@email.co"]
_pass = "xxxxxx"
server.login(_from, _pass)
msg = "\r\n".join([
"From: "+_from,
"To: "+_to,
"CC: "+",".join(_cc),
"Subject: Ouchh!! "+_proc+" again is down.",
"",
"Again " + _proc + " is down. The service was restarted!!"
])
server.sendmail(_from, _to, msg)
server.quit()
print "*** email send ***\n"
It works fine in my console when I execute the below command:
python /home/check-services.py
Everything looks okay. I try setting up the cron job in the webmin server and it should execute every minute but it doesn't. This is the cron's log:
(root) CMD (python /home/check-services.py) every minute, like we already was configurated.
I don't see anything abnormal but it's still no working. I appreciate all your help.
Python version 2.7.
EDIT: I just saw the email in /var/email/root and it show this:
Traceback (most recent call last):
File "/home/check-services.py", line 77, in <module>
p = subprocess.Popen(["service", _proc, "status"], stdout=subprocess.PIPE)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
The problem is that service
isn't in any of the directories listed in the $PATH of the cron process.
There are many solutions. One solution is to specify the complete path to service
in your .Popen()
call. On my computer, that is /usr/sbin/service
.
Try this:
p = subprocess.Popen(
["/usr/sbin/service", _proc, "status"], stdout=subprocess.PIPE)
Another solution is to specify a different $PATH in your crontab:
* * * * * PATH=/bin:/usr/bin:/sbin:/usr/sbin /usr/bin/python /home/check-services.py