首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >除错误外,无法捕获某些Python DBus

除错误外,无法捕获某些Python DBus
EN

Unix & Linux用户
提问于 2020-02-11 01:16:22
回答 1查看 962关注 0票数 0

我在Python中得到了这个错误,它不是致命的,我假定它是写到stderr中的:

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

对不起,非正统的“引号”而不是code块。我想把滚动圈往右转8英里。

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

代码语言:javascript
复制
    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

然而,它只是生成我的以外,这是之前的大部分错误消息。但它并不能抑制以前的错误消息,通常会发生这种情况?

代码语言:javascript
复制
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“拒绝访问”错误,缩写如下:

代码语言:javascript
复制
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.6LTS,内核4.14.170,Gnome 3.18)。我不想纠正这些错误。对于我的项目,我不需要检查这些DBus服务。我只想抑制错误信息。

FWIW I“还获得了两个会话服务DBUS错误,我可以成功地捕获:

代码语言:javascript
复制
==============   Session services   ================

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

我认为从这个帖子那里他们可能不得不逃跑(如\- )。这些错误真正意味着什么,以及如何修复它们也将是很好的。

FWIW这里是我的代码:

代码语言:javascript
复制
    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
EN

回答 1

Unix & Linux用户

发布于 2020-02-19 02:53:32

原来,由于系统上的dbus的“设计缺陷”,我不是第一个遇到这个问题的人。解决办法是这样做:

代码语言:javascript
复制
    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])

对于所有的评论,我感到很抱歉,但与其删除它们(或者更糟的是重写它们),不如把它们保留在原处。

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

代码语言:javascript
复制
        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)

奖励答案..。将-从对象路径名称中删除:

代码语言:javascript
复制
    if "-" in object_path :
        # Bug: https://bugs.launchpad.net/snappy/+bug/1449722
        object_path = object_path.replace("-", "")
票数 0
EN
页面原文内容由Unix & Linux提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://unix.stackexchange.com/questions/566868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档