我想使用python检查一些服务状态(如MySQL,Apache2)。我写了一个简单的脚本。
#!/usr/bin/python
from subprocess import call
command = raw_input('Please enter service name : ')
call(["/etc/init.d/"+command, "status"])
此脚本将请求用户输入服务并在终端上显示其结果,如下所示。
● apache2.service - LSB: Apache2 web server
Loaded: loaded (/etc/init.d/apache2)
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: active (running) since සි 2016-06-17 09:16:10 IST; 5h 43min ago
Docs: man:systemd-sysv-generator(8)
Process: 2313 ExecReload=/etc/init.d/apache2 reload (code=exited, status=0/SUCCESS)
Process: 1560 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS)
CGroup: /system.slice/apache2.service
├─1941 /usr/sbin/apache2 -k start
├─2332 /usr/sbin/apache2 -k start
├─2333 /usr/sbin/apache2 -k start
├─2334 /usr/sbin/apache2 -k start
├─2335 /usr/sbin/apache2 -k start
└─2336 /usr/sbin/apache2 -k start
我只想为每个服务Active: active (running)
取一行,并检查是否正在运行,如果不是,我想问你是否要启动它。
有人可以帮我这么做吗?提前致谢
答案 0 :(得分:1)
我认为你想要的是捕获输出。有点像:
status = subprocess.check_output("YOUR COMMAND", shell=True)
if ("Active: active (running)" in status):
...