无法捕获某些 Python DBus(错误除外)

无法捕获某些 Python DBus(错误除外)

我在 Python 中遇到这个非致命错误,我假设已写入stderr

错误:dbus.proxies:内省错误:1.4:/org/freedesktop/Thermald:dbus.exceptions.DBusException:org.freedesktop.DBus.Error.AccessDenied:拒绝发送消息,2个匹配的规则; type =“method_call”,sender =“:1.974”(uid = 1000 pid = 20020 comm =“/usr/bin/python ./mmm”)interface =“org.freedesktop.DBus.Introspectable”成员=“Introspect”错误name =“(未设置)”requested_reply =“0”目的地=“:1.4”(uid = 0 pid = 1309 comm =“/ usr / sbin / Thermald --no-daemon --dbus-enable”)

抱歉用非正统的“引用”而不是code块。我想节省向右滚动 8 英里的时间。

我可以用以下方法捕获错误:

    except dbus.exceptions.DBusException as err:
        # Same as dbus.DBusException
        print('\ndbus.exceptions.DBusException:', service)
        print(err.message+'\n')
        return False
    except dbus.DBusException as err:
        # Same as dbus.exceptions.DBusException
        print('\ndbus.DBusException:', service)
        print(err.message+'\n')
        return False

然而它只是生成我的 except 这是最多之前的错误消息。但它并没有抑制通常发生的先前错误消息???

dbus.exceptions.DBusException: org.freedesktop.thermald
Rejected send message, 2 matched rules; type="method_call", sender=":1.974" (uid=1000 pid=20020 comm="/usr/bin/python ./mmm ") interface="org.freedesktop.DBus.Introspectable" member="Introspect" error name="(unset)" requested_reply="0" destination=":1.4" (uid=0 pid=1309 comm="/usr/sbin/thermald --no-daemon --dbus-enable ")

我总共收到 4 个系统服务 DBus“访问被拒绝”错误,缩写如下:

ERROR:dbus.proxies:Introspect error on :1.19:/fi/epitest/hostap/WPASupplicant:
ERROR:dbus.proxies:Introspect error on :1.19:/fi/w1/wpa_supplicant1:
ERROR:dbus.proxies:Introspect error on :1.20:/org/freedesktop/NetworkManager/dnsmasq:
ERROR:dbus.proxies:Introspect error on :1.4:/org/freedesktop/thermald:

这些似乎都是常见的 Ubuntu 错误(我使用的是 16.04.6 LTS,内核 4.14.170,Gnome 3.18)。我不想修复这些错误。对于我的项目,我不需要检查这些 DBus 服务。我只是想抑制错误消息。

FWIW 我还收到两个会话服务 DBUS 错误成功捕获:


==============   Session services   ================

Object path: '/org/freedesktop/network-manager-applet' contains invalid character '-'
Object path: '/org/nautilus-actions/DBus' contains invalid character '-'

我认为由此邮政他们可能必须被转义,例如\-。这些错误的真正含义以及如何修复它们也很好。

FWIW 再次是我的代码:

    def refresh_listdata(self, listdata):

        import json

        # If we delete list and append nothing appears (garbage collecctor).
        # listdata = []

        listdata *= 0   # https://stackoverflow.com/a/44349418/6929343

        bus = dbus.SystemBus()
        print ('\n=============   System services   =================\n')

        for service in dbus.SystemBus().list_names():
            # Skip over ":1.20", ":1.65", etc.
            if not service.startswith(":") :
                # print(service)
                object_path=service.replace(".", "/")
                object_path = "/" + object_path
                dictionary = self.rec_intro(bus, service, object_path)
                # print(dictionary)
                if dictionary != False :
                    listdata.append(dictionary)

        bus = dbus.SessionBus()
        print ('\n==============   Session services   ================\n')

        for service in dbus.SessionBus().list_names():
            if not service.startswith(":") :
                # print(service)
                object_path=service.replace(".", "/")
                object_path = "/" + object_path
                dictionary = self.rec_intro(bus, service, object_path)
                # print(dictionary)
                if dictionary != False :
                    listdata.append(dictionary)

#        print ("\nlistdata[0]\n", listdata[0])
#        print(json.dumps(listdata[0], indent=4, sort_keys=True))

    def rec_intro(self, bus, service, object_path, 
                       paths=None, serviceDict=None):

        from xml.etree import ElementTree

        #print(object_path)
        if paths == None:
            paths = {}
        paths[object_path] = {}

        if "-" in object_path :
            print ("Object path: '" + object_path + \
            "' contains invalid character '-'")
            return False

        try:
            obj = bus.get_object(service, object_path)
        except:
            print('Cannot get object: ', service, object_path)
            return False

        try:
            iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable')
        except:
            print('Interface error:', obj)
            return False

        try:
            xml_string = iface.Introspect()
#        except DBusException as err:
#            # NOT DEFINED!
#            print('\nDBusException:', service)
#            print(err.message+'\n')
#            return False
        except dbus.proxies as err:
            print('\ndbus.proxies:Introspect error:', service)
            print(err.message+'\n')
            return False
#        except org.freedesktop.DBus.Error.AccessDenied as err:
#            # NOT DEFINED!
#            print('\norg.freedesktop.DBus.Error.AccessDenied:', service)
#            print(err.message)
#            return False
        except dbus.exceptions.DBusException as err:
            # Same as dbus.DBusException
            print('\ndbus.exceptions.DBusException:', service)
            print(err.message+'\n')
            return False
        except dbus.DBusException as err:
            # Same as dbus.exceptions.DBusException
            print('\ndbus.DBusException:', service)
            print(err.message+'\n')
            return False
        except:
            print('No permissions to:', bus, service, object_path)
            return False

        for child in ElementTree.fromstring(xml_string):
            if child.tag == 'node':
                if object_path == '/':
                    object_path = ''
                new_path = '/'.join((object_path,
                                     child.attrib['name']))
                self.rec_intro(bus, service, new_path)
            else:
                if object_path == "":
                    object_path = "/"
                functiondict = {}
                paths[object_path][child.attrib["name"]] = functiondict
                for func in child.getchildren():
                    if func.tag not in functiondict.keys():
                        functiondict[func.tag] = []
                    functiondict[func.tag].append(func.attrib["name"])

        if serviceDict == None:
            serviceDict = {}
        serviceDict[service] = paths
        return serviceDict

答案1

事实证明,由于 dbus over systemd 的“设计缺陷”,我并不是第一个遇到此问题的人。解决方案是这样的:

    def BuildNoPermissions(self, bus):
        ''' Errors add 5 seconds:

        ERROR:dbus.proxies:Introspect error on :1.4:/org/freedesktop/thermald:
        dbus.exceptions.DBusException: org.freedesktop.DBus.Error.AccessDenied:

        Trap this error by first:
        Build list of objects with no introspection.

        Add to list if entry:
            <policy context="default">
                <deny own="fi.epitest.hostap.WPASupplicant"/>
                <deny own="fi.w1.wpa_supplicant1"/>
            </policy>
        ...exists. Add each deny entry to list to trap error:
        ERROR:dbus.proxies:Introspect error on :1.19:/fi/w1/wpa_supplicant1 ...

        Then before introspecting dbus make sure item isn't on list. If it is
        on list then create necessary "No permissions" entry instead.

        Now all that is left is:

        ERROR:dbus.proxies:Introspect error on :1.1450:/org/freedesktop/
        NetworkManager/dnsmasq:

        Found in:
        /etc/dbus-1/system.d/org.freedesktop.NetworkManager.conf:
                        <deny own="org.freedesktop.NetworkManager.dnsmasq"/>

        Problem is NetworkManager has Introspect but denies dnsmasq so check
        deny for all *.conf files even ones with introspect.

        NOTE: when running with sudo things get worse:

        ERROR:dbus.proxies:Introspect error on :1.19:/fi/epitest/hostap/
        WPASupplicant/Interfaces/62: dbus.exceptions.DBusException:
        org.freedesktop.DBus.Error.NoReply: Message recipient disconnected 
        from message bus without replying

        ... and then Ubuntu prints system crash message with option to report.
        '''
#        print ('\n=============   BuildNoPermissions   =================\n')
#        print (bus, '\n')
        result = os.popen("grep -Li introspect /etc/dbus-1/system.d/*"). \
                          read().splitlines()

        for line in result:
            base=os.path.basename(line)     # remove path prefix
            base=os.path.splitext(base)[0]  # remove extension suffix
            ''' Must open up file to see if <deny> is used and add them
            '''
#            print (base)
            self.NoPermissions.append(base)

        result = os.popen("grep 'deny own' /etc/dbus-1/system.d/*"). \
                          read().splitlines()
        for deny in result:
            # [1::2] is a slicing which extracts odd values
            d = deny.split('"')[1::2]
            self.NoPermissions.append(d[0])
            # Only 1 per line, so take index 0
            # print (d[0])

对所有评论感到抱歉,但最好将它们保留在原处,而不是删除它们(或更糟糕的是重写它们)。

为了调用例程,修改了原始函数:

        bus = dbus.SystemBus()
        self.BuildNoPermissions(bus)
#        print ('\n=============   System services   =================\n')
#        print (self.NoPermissions, '\n')
        for service in bus.list_names():
            # Skip over ":1.20", ":1.65", etc.
            if not service.startswith(":") :
                denied = False
                for deny in self.NoPermissions:
                    if deny == service:
                        denied = True
                        break
                if denied: continue

                # print(service)
                object_path=service.replace(".", "/")
                object_path = "/" + object_path
                dictionary = self.rec_intro(bus, service, object_path)
                # print(dictionary)
                if dictionary != False :
                    listdata.append(dictionary)

额外的答案...去掉-对象路径名称:

    if "-" in object_path :
        # Bug: https://bugs.launchpad.net/snappy/+bug/1449722
        object_path = object_path.replace("-", "")

相关内容