如何知道是否安装了服务 [英] How to know if a service is installed

查看:155
本文介绍了如何知道是否安装了服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用Python脚本检查是否已安装服务的方法.例如,如果我要检查命令行中已安装/正在运行/已关闭的SSH服务器,则可以使用:

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)

因此,我使用子过程check_output来获得这三行代码,但是python脚本无法正常工作.我使用了 shell = True 来获取输出,但是它不起作用.找到服务是否已安装或其他方法是否存在并且效率更高的解决方案是正确的解决方案?

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?

有我的python脚本:

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"

此代码的问题是一个subprocess.CalledProcessError:命令返回了非零退出状态1.我知道那是命令行返回不存在的内容的时候,但是当我在shell中写命令时我需要结果

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

推荐答案

只需捕获错误并避免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)

这篇关于如何知道是否安装了服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆