在ubuntu登录之前如何在python守护进程中使用DBUS

问题描述

(背景:我最近看到了一个很棒的Android应用程序,它与linux配对,允许用户解锁和锁定锁屏。但是,该项目不再正常工作和维护了。我正在尝试使其正常运行,但是有一个DBUS问题)

创建了一个守护程序服务,该服务打开一个套接字并等待传入​​连接。收到连接后,它将尝试获取DBUS_ADDRESS和UID并将其设置为环境变量:

os.environ['DBUS_SESSION_BUS_ADDRESS'] = DBUS_ADDRESS
os.seteuid(UID)

这就是我获取DBUS和UID地址的方式:

def get_bus_and_uid():
    '''Find the first running process with a DBUS session address run by
    a non-daemon user,and return both the DBUS_SESSION_BUS_ADDRESS and the
    uid.'''

    DBUS_ADDRESS = 'DBUS_SESSION_BUS_ADDRESS'
    UIDS = 'uids'

    # Find all non-daemon users.
    all_users = [i.split(':') for i in open('/etc/shadow').readlines()]
    users = [i[0] for i in all_users if i[1] not in ('!','*')]

    # Find the first non-daemon user process with a DBUS_SESSION_BUS_ADDRESS
    # in it's environment.
    user_address = {}
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid','username',UIDS])
        except psutil.NoSuchProcess:
            pass
        user = pinfo['username']

        # Ignore process run by daemons.
        if user not in users:
            continue

        environ = psutil.Process(pid=pinfo['pid']).environ()

        
        if DBUS_ADDRESS in environ:
            # pinfo[uids] returns real,effective and saved uids.
            return environ[DBUS_ADDRESS],pinfo[UIDS][0]
    return None,None

但是,如果在至少一个用户登录后对get_bus_and_uid()进行了调用,这将起作用。如果在首次登录之前进行任何连接,则此操作将失败。

我尝试了什么: 我试图通过守护程序通过$ dbus-launch启动DBUS服务,但还是没有运气。 有没有其他方法可以使用DBUS与org。(gnome | freedesktop).screensaver通信?

(这样做是为了与org。(gnome | freedesktop).screensaver通信。

github中的项目:Remote-linux-unlocker/unlocker-daemon.py

感谢您的帮助,谢谢。

编辑:如果没有活动的桌面会话,也没有任何要解锁的内容。感谢您的澄清@tripleee

解决方法

如果会话与systemd-logind集成在一起(GNOME,Cinnamon和KDE都支持它),

loginctl unlock-sessions

将解锁所有会话。