使用 python 从 dbus 获取 'state'

Get 'state' from dbus using python

我想在 python 中做一件非常简单的事情 - 通过 dbus 从 firewalld 读取状态 - "org.freedesktop.DBus.Properties"。

根据https://firewalld.org/documentation/man-pages/firewalld.dbus.html

state - s - (ro)
firewalld state. This can be either INIT or RUNNING. In INIT state, firewalld is starting up and initializing.

我从 linux 找到了如何使用 dbus-send 来完成它,但我在 python.

中就是做不到。

这是对我的问题最接近的 SO 答案,但我仍然无法弄明白。 [

Here's how to do it in shell:
firewall-cmd --state
running 

And with dbus-send:
dbus-send --system --print-reply --dest=org.fedoraproject.FirewallD1 /org/fedoraproject/FirewallD1 org.freedesktop.DBus.Properties.Get string:"org.fedoraproject.FirewallD1" string:"state"
method return time=1563593597.133270 sender=:1.2 -> destination=:1.116 serial=691 reply_serial=2
   variant       string "RUNNING"
# Here's my incorrect code:
import dbus
Bus = dbus.SystemBus()
Proxy = Bus.get_object('org.fedoraproject.FirewallD1', '/org/fedoraproject/FirewallD1')
Proxy.Get('state', dbus_interface='org.freedesktop.DBus.Properties')

这是我从 python 收到的错误消息:

ERROR:dbus.connection:Unable to set arguments ('state',) according to signature 'ss': <class 'TypeError'>: More items found in D-Bus signature than in Python arguments
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 70, in __call__
    return self._proxy_method(*args, **keywords)
  File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 145, in __call__
    **keywords)
  File "/usr/lib/python3/dist-packages/dbus/connection.py", line 641, in call_blocking
    message.append(signature=signature, *args)
TypeError: More items found in D-Bus signature than in Python arguments
>>> 

解决方法如下:

Proxy.Get('org.fedoraproject.FirewallD1', 'state', dbus_interface='org.freedesktop.DBus.Properties')

问题在于 org.freedesktop.DBus.Properties 接口的 Get 方法实际上采用两个参数接口来访问 属性 和 属性 的名称:

org.freedesktop.DBus.Properties.Get (in STRING interface_name,
                                     in STRING property_name,
                                     out VARIANT value);

来自https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties

import dbus
Bus = dbus.SystemBus()
Proxy = Bus.get_object('org.fedoraproject.FirewallD1', '/org/fedoraproject/FirewallD1')
Proxy.Get('org.fedoraproject.FirewallD1', 'state', dbus_interface='org.freedesktop.DBus.Properties')

由于我没有特定的 DBus 服务或对象,因此使用不同的常量进行了测试。