Anibal Mauricio Anibal Mauricio - 3 months ago 13
Python Question

What is wrong with my python script and cron job?

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!"
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('', 587)
_from = ""
_to = ""
_cc = [""]
_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)
print "*** email send ***\n"

It works fine in my console. If I type:

python /home/

Everything is okay. I set 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/ 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.

I just saw the email in /var/email/root and it show this:

Traceback (most recent call last):
File "/home/", line 77, in <module>
p = subprocess.Popen(["service", _proc, "status"], stdout=subprocess.PIPE)
File "/usr/lib/python2.7/", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/", 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/