Python crontab subprocess and service restart

I have a small python code that restarts nginx on it that does not exist. When I run sudo python monitor_server.py, everything is fine. When I tried cron cron cron ( sudo crontab -e) with the line:
* * * * * python /root/monitor_server.py > /var/log/my_monitor/cron_log.log 2>&1 I get:

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

The code:

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')
+4
source share
1 answer

Try calling the command using an absolute path, since you are invoking it without a shell and under a different user account, some commands are not available without specifying an absolute path.

First find where the command is located:

$ which service
/usr/sbin/service

Then change your code to:

def restart_service(name):
    command = ['/usr/sbin/service', name, 'restart'];
    #shell=FALSE for sudo to work.
    subprocess.call(command, shell=False)
+3
source

Source: https://habr.com/ru/post/1544133/


All Articles