使用 python 从 dbus 获取'state'



我想在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答案,但我仍然无法弄清楚。[dbus_to_python(( 正好需要 1 个参数?

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
>>> 

问题是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 服务或对象。

这是解决方案:

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

相关内容

  • 没有找到相关文章

最新更新