一部の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") インターフェイス="org.freedesktop.DBus.Introspectable" member="Introspect" エラー名="(設定しない) " request_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

しかし、それは私の除外だけを生成します。最大以前のエラーメッセージ。しかし、一般的に発生する以前のエラーメッセージは抑制されませんか? ? ?

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また、2つのセッションサービス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

ご存じのとおり、systemdのdbusの「設計上の欠陥」のためにこの問題が発生したのは私が初めてではありません。解決策は次のとおりです。

    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("-", "")

おすすめ記事