How to know if a service is installed
Asked Answered
Y

2

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

Yeoman answered 11/7, 2016 at 18:35 Comment(1)
Does this answer your question? Check if service exists with AnsibleForte
P
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)
Piefer answered 11/7, 2016 at 19:48 Comment(2)
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 notYeoman
It works, I forgot to send stderr to stdout, the output will be in e.output on errorPiefer
H
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?

Hakon answered 11/7, 2016 at 19:42 Comment(1)
I need to adapt my script but it's working even if the service is stopped. Thanks you!!Yeoman
P
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)
Piefer answered 11/7, 2016 at 19:48 Comment(2)
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 notYeoman
It works, I forgot to send stderr to stdout, the output will be in e.output on errorPiefer

© 2022 - 2024 — McMap. All rights reserved.