1

I'm looking for a way to check with a Python script if a service is installed. For example, if I want to check than a SSH server in installed/running/down in command line, I used :

service sshd status

If the service is not installed, I have a message like this:

sshd.service
  Loaded: not-found (Reason: No such file or directory)
  Active: inactive (dead)

So, I used a subprocess check_output to get this three line but the python script is not working. I used shell=True to get the output but it doen't work. Is it the right solution to find if a service is installed or an another method is existing and much more efficient?

There is my python script:

import subprocess
from shlex import split

output = subprocess.check_output(split("service sshd status"), shell=True)

if "Loaded: not-found" in output:
    print "SSH server not installed"

The probleme with this code is a subprocess.CalledProcessError: Command returned non-zero exit status 1. I know that's when a command line return something which doesn't exist but I need the result as I write the command in a shell

Max_xaM
  • 17
  • 1
  • 4
  • Does this answer your question? [Check if service exists with Ansible](https://stackoverflow.com/questions/30328506/check-if-service-exists-with-ansible) – Thor Jan 07 '20 at 01:02

2 Answers2

3

Choose some different systemctl call, which differs for existing and non-existing services. For example

systemctl cat sshd

will return exit code 0 if the service exists and 1 if not. And it should be quite easy to check, isn't it?

Jakuje
  • 24,773
  • 12
  • 69
  • 75
0

Just catch the error and avoid shell=True:

import subprocess

try:
    output = subprocess.check_output(["service", "sshd", "status"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    print(e.output)
    print(e.returncode)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • The program told me that : Command '['service','shd','status']' returned non-zero exit status 3. It's not the same line as the shell command and I can't know if the service is installed or not – Max_xaM Jul 11 '16 at 20:20
  • It works, I forgot to send stderr to stdout, the output will be in `e.output` on error – Padraic Cunningham Jul 11 '16 at 20:27