我有一个小的python代码重新启动它不存在的nginx。
当我跑sudo python monitor_server.py
时一切都很好。
当我尝试使用root cron(sudo crontab -e
)时使用以下行来表示它:
* * * * * python /root/monitor_server.py > /var/log/my_monitor/cron_log.log 2>&1
我明白了:
Traceback (most recent call last):
File "/root/monitor_server.py", line 19, in <module>
restart_service('mongod')
File "/root/monitor_server.py", line 10, in restart_service
subprocess.call(command, shell=False)
File "/usr/lib64/python2.6/subprocess.py", line 478, in call
p = Popen(*popenargs, **kwargs)
File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1234, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
代码:
def restart_service(name):
command = ['service', name, 'restart'];
#shell=FALSE for sudo to work.
subprocess.call(command, shell=False)
if __name__ == '__main__':
try:
f = urllib2.urlopen("<healthcheck URL>")
except (urllib2.HTTPError, urllib2.URLError) as e:
logging.log(logging.ERROR, 'restarting server')
restart_service('nginx')
答案 0 :(得分:3)
尝试使用绝对路径调用命令,因为在没有shell的情况下调用它,在另一个用户帐户下,如果没有指定绝对路径,则某些命令不可用。
首先找到,命令位于何处:
$ which service
/usr/sbin/service
然后将您的代码更改为:
def restart_service(name):
command = ['/usr/sbin/service', name, 'restart'];
#shell=FALSE for sudo to work.
subprocess.call(command, shell=False)