gpt4 book ai didi

python - 如何从 Python 获取失败服务的 systemctl 结果?

转载 作者:行者123 更新时间:2023-12-01 23:41:15 25 4
gpt4 key购买 nike

如果 systemd 服务单元处于故障状态,systemctl status 会显示这一事实:

    # systemctl status myservice
● myservice.service - Important Crash Prone service (myservice)
Loaded: loaded (/etc/systemd/system/myservice.service; enabled; vendor preset: disabled)
Active: failed (Result: start-limit) since Tue 2017-08-22 20:04:13 UTC; 3s ago
Process: 31108 ExecStart=/bin/myservice (code=dumped, signal=ABRT)
Main PID: 31108 (code=dumped, signal=ABRT)

我想让一个 Python 程序获取“Result: start-limit”字段,而无需 fork systemctl 并尝试解析输出。其他字段(例如 Loaded、Active)可从 Python dbus 库获取。

例如,以下代码获取 ActiveState 属性,该属性由 systemctl 在“Active:”(上面输出中的单词“failed”)之后显示。

from dbus import Interface, SystemBus, SessionBus
bus = SystemBus()
systemd = bus.get_object('org.freedesktop.systemd1',
'/org/freedesktop/systemd1')

manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')

myservice_unit = manager.LoadUnit('myservice.service')

myservice_proxy = bus.get_object('org.freedesktop.systemd1', str(myservice_unit))

myservice = Interface(myservice_proxy,
dbus_interface='org.freedesktop.systemd1.Unit')

prop = 'ActiveState'
value = myservice_proxy.Get('org.freedesktop.systemd1.Unit',
prop,
dbus_interface='org.freedesktop.DBus.Properties')
print("{} is: {}".format(prop, value))

看起来“Result”值并不是像其他许多输出那样的属性。

最佳答案

如果您查看https://www.freedesktop.org/wiki/Software/systemd/dbus/处的文档,它解释了Result服务单元对象(org.freedesktop.systemd1.Service)的一部分。

所以,我将其添加到您的代码中:

if value == 'failed':
result_prop = 'Result'
result = myservice_proxy.Get('org.freedesktop.systemd1.Service',
result_prop,
dbus_interface='org.freedesktop.DBus.Properties')
print(result)

现在它工作得很好!

关于python - 如何从 Python 获取失败服务的 systemctl 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45826461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com