我的python脚本和cron作业有什么问题?

时间:2016-07-13 16:30:19

标签: python cron-task

我有这个python脚本来检查像MySQL和Apache这样的服务,如果其中一些服务器出现问题,那么它会再次启动:

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"

当我执行以下命令时,它在我的控制台中正常工作:

  

python /home/check-services.py

一切看起来都不错。我尝试在webmin服务器中设置cron作业,它应该每分钟执行一次,但事实并非如此。这是cron的日志:

每分钟

(root)CMD(python /home/check-services.py),就像我们已经配置好一样。

我没有看到任何异常,但它仍然没有用。我感谢你的帮助。

Python 2.7版。

编辑: 我刚看到/ var / email / root中的电子邮件,它显示了这个:

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

1 个答案:

答案 0 :(得分:3)

问题是service不在cron进程的$ PATH中列出的任何目录中。

有很多解决方案。一种解决方案是在service来电中指定.Popen()的完整路径。在我的计算机上,即/usr/sbin/service

试试这个:

p = subprocess.Popen(
    ["/usr/sbin/service", _proc, "status"], stdout=subprocess.PIPE)

另一种解决方案是在crontab中指定不同的$ PATH:

* * * * * PATH=/bin:/usr/bin:/sbin:/usr/sbin /usr/bin/python /home/check-services.py