如何从 systemctl status 的输出中获取单个值

how to get individual values from the output of systemctl status

[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 脚本检索服务名称、正常运行时间和状态。

systemctl status 有一个选项 --output that allows to use the options of journalctl

尝试 JSON 可以很容易地被 Python 解析:

$ sudo systemctl status --output=json-pretty nginx

您可以使用 subprocess.check_output() 从 systemctl 获取输出并在之后解析它。

或许您可以尝试 regular expression 来解析输出。这是我用过的。请大家看看和评论。

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

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

systemd 服务具有完整的属性列表。例如获取开始时间;你可以 运行:

systemctl show your.service --property=ActiveEnterTimestamp

这会给出类似的东西:

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

查看所有属性列表;只是 运行

systemctl show your.service