4
[root@localhost etc]# systemctl status blu_av
● blu_av.service - avscan
   Loaded: loaded (/etc/systemd/system/blu_av.service; disabled; vendor preset: disabled)
   Active: active (running) since Fri 2018-03-16 16:31:14 IST; 3s ago
 Main PID: 31934 (av)
   CGroup: /system.slice/blu_av.service
           ├─31934 /opt/services/av
           └─31956 /opt/services/av

Mar 16 16:31:14 localhost.localdomain systemd[1]: Started avscan.
Mar 16 16:31:14 localhost.localdomain systemd[1]: Starting avscan...

如果以上是我状态的输出。我想使用 python 脚本检索服务名称、正常运行时间和状态。

4

4 回答 4

12

systemdservices 有一个完整的属性列表。例如获取开始时间;你可以运行:

systemctl show your.service --property=ActiveEnterTimestamp

这会给出类似的东西:

ActiveEnterTimestamp=Fri 2019-05-03 09:35:02 CEST

查看所有属性的列表;赶紧跑

systemctl show your.service
于 2019-05-03T08:38:05.160 回答
5

systemctl status有一个选项--output允许使用 的选项journalctl

试试 Python 可以轻松解析的 JSON:

$ sudo systemctl status --output=json-pretty nginx
于 2018-03-16T13:47:02.587 回答
3

也许您可以尝试 正则表达式来解析输出。这是我用的。请查看并发表评论。

import subprocess, re

def read_status(service):
    p =  subprocess.Popen(["systemctl", "status",  service], stdout=subprocess.PIPE)
    (output, err) = p.communicate()
    output = output.decode('utf-8')

    service_regx = r"Loaded:.*\/(.*service);"
    status_regx= r"Active:(.*) since (.*);(.*)"
    service_status = {}
    for line in output.splitlines():
        service_search = re.search(service_regx, line)
        status_search = re.search(status_regx, line)

        if service_search:
            service_status['service'] = service_search.group(1)
            #print("service:", service)

        elif status_search:
            service_status['status'] = status_search.group(1).strip()
            #print("status:", status.strip())
            service_status['since'] = status_search.group(2).strip()
            #print("since:", since.strip())
            service_status['uptime'] = status_search.group(3).strip()
            #print("uptime:", uptime.strip())

    return service_status

def main():
    service = 'mysql'
    reponse = read_status(service)

    for key in reponse:
        print('{}:{}'.format(key, reponse[key]))


if __name__ == '__main__':
    main()

输出:

service:mysql.service
status:active (running)
since:Fri 2018-03-16 09:17:57 CET
uptime:6h ago

我只是用来检查我的正则表达式。

于 2018-03-16T14:43:59.307 回答
0

您可以通过使用从 systemctl 获取输出,subprocess.check_output()然后对其进行解析。

于 2018-03-16T13:48:01.780 回答