如果安装了服务,我正在寻找一种检查Python脚本的方法。例如,如果我想在命令行中检查安装/运行/关闭的SSH服务器,我使用了:
service sshd status
如果未安装该服务,我会收到如下消息:
sshd.service
Loaded: not-found (Reason: No such file or directory)
Active: inactive (dead)
所以,我使用了一个子进程check_output来获取这三行,但是python脚本无效。我使用 shell = True 来获取输出,但它不起作用。它是找到服务是否安装或另一种方法是否存在且效率更高的正确解决方案?
有我的python脚本:
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中编写命令
答案 0 :(得分:0)
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?
答案 1 :(得分: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)