1

I want to get a service status and if it's not up, to send the status (stdout) in email.
This script is scheduled to run every hour by cron.
When running manually, the following works fine:

def is_service_running(name):
    with open(os.devnull, 'wb') as hide_output:
        proc = subprocess.Popen(['service', name, 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        output = proc.stdout.read()
        exit_code = proc.wait()
        return exit_code == 0, output

But when running by cron. output is empty.
How can I capture stdout when running by cron? Thank you

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
SagiLow
  • 5,721
  • 9
  • 60
  • 115
  • Does it work if you use `result = subprocess.run(['service', name, 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)` and then `output = result.stdout`? – ndmeiri Jun 14 '18 at 15:18
  • In this case the script fails to run by cron and produce `file not found` error. the `shell=True` must stay – SagiLow Jun 15 '18 at 09:16
  • You replied to the wrong comment thread. – ndmeiri Jun 15 '18 at 11:19

1 Answers1

0

The problem wasn't cron but shell=True.
Apparently, when using shell=True, popen expects single string and not a list.
So when I updated my call to:

proc = subprocess.Popen(['service ' + name + ' status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

everything worked.

SagiLow
  • 5,721
  • 9
  • 60
  • 115
  • Actually, removing `shell=True` would be a much better fix. See also https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess – tripleee Jun 15 '18 at 09:28
  • @tripleee if I set shell to false, I get the following error when running by cron: `OSError: [Errno 2] No such file or directory` – SagiLow Jun 15 '18 at 12:51
  • It's not clear what causes that, try `e = os.environ.copy(); e.update({'PATH': os.environ['PATH'] + ':/usr/sbin'); proc = subprocess.Popen(..., env=e)` but this is pure speculation. Fixing the error is still a better solution than calling a shell. – tripleee Jun 15 '18 at 18:19