问题原文
原帖链接 · Stanislav Ivanov · CC BY-SA 3.0
I want to get service status details (Loaded, enabled, active, running, since, Main PID) in machine readable form and I know that systemd tools have --output=json option, but if I do:
systemctl status servicename --output=json --plain
I see something like:
● snapd.service - Snappy daemon
Loaded: loaded (/lib/systemd/system/snapd.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2018-04-16 11:20:07 MSK; 4h 45min ago
Main PID: 738 (snapd)
Tasks: 10 (limit: 4915)
CGroup: /system.slice/snapd.service
└─738 /usr/lib/snapd/snapd
{ "__CURSOR" : "s=461ecb6a4b814913acd57572cd1e1c82;...
Journal records are in JSON. But how to get the service status in JSON if it's possible?
已采纳解答
原帖链接 · Stanislav Ivanov · CC BY-SA 4.0
Simple way to getting service status in machine readable form:
systemctl show --no-pager servicename
This command outputs data in key=value format:
Type=notify
Restart=always
NotifyAccess=main
...
If JSON format is required, you can use the following simple Python script (Python 2 and 3 compatible) get_service_info.py:
import os, sys, subprocess, json
key_value = subprocess.check_output(["systemctl", "show", sys.argv[1]], universal_newlines=True).split('\n')
json_dict = {}
for entry in key_value:
kv = entry.split("=", 1)
if len(kv) == 2:
json_dict[kv[0]] = kv[1]
json.dump(json_dict, sys.stdout)
Usage:
get_service_info.py servicename
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
