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

标签 python systemd

如果 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/

相关文章:

python - 设置 virtualenv 文件夹时出错

python - 如果从不同的 View 函数调用,则不会传递上下文数据

python - 作业因阶段失败而中止 : Task 5 in stage 3. 0 失败 1 次

dns - 使用 systemd 在 OS 上为 Docker 守护程序设置 DNS

python - uwsgi 在作为 systemd 服务运行时损坏管道

python - 在python中将3d列表转换为2d列表

python - 无法从父目录加载 Flask 配置

python - Systemd 服务不执行我的 Python 脚本

linux - pgagent 的 systemd 单元

node.js - 为什么运行 Node.js 应用程序的 systemd 服务在正常停止时显示失败状态?