如何从 systemd 用户服务访问会话 D-Bus?
Posted
技术标签:
【中文标题】如何从 systemd 用户服务访问会话 D-Bus?【英文标题】:How to access session D-Bus from systemd user service? 【发布时间】:2016-12-02 02:29:02 【问题描述】:我有运行 shell 脚本的用户服务,它试图像这样访问我的会话的锁屏状态:
# Test Unity screen-lock:
isLocked()
isLocked=$(gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked)
lock()
if [[ $isLocked == "(false,)" ]]; then
gnome-screensaver-command -l
elif [[ $isLocked == "(true,)" ]]; then
exit 1
fi
exit 0
问题是服务“是每个用户的进程,而不是每个会话”,我不知道如何访问会话 dbus:
GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name com.canonical.Unity was not provided by any .service files
【问题讨论】:
这段代码中是否设置了 DBUS_SESSION_BUS_ADDRESS 变量? 不,不是。应该是? 据我所知,它需要连接到总线,并且 pam_systemd 应该在您登录时设置它。如果没有设置,则会启动一个新的 dbus,您将无法与其他事物交谈。我对这些都不太了解,所以不要相信我的话。 【参考方案1】:我也遇到了同样的问题,但我的研究一无所获。如果有人能找到更好的方法来查询 Unity 的锁定状态,我很想听听。
我最近了解了命名管道,当时我想知道我可以用这种东西做什么。事实证明,这个问题恰好是一个完美的应用程序。
创建以下脚本...
#!/bin/bash
# this script is meant to be called in two different ways.
# 1. It can be called as a service by passing "service" as the first argument. In this
# mode, the script listens for requests for lock screen status. The script should be
# run in this mode with startup applications on user logon.
# 2. If this script is called without any arguments, it will call the service to request
# the current lock screen status. Call this script in this manner from your user
# service.
# this will be the named pipe we'll use for requesting and receiving screen lock status
pipe="/tmp/lockscreen-status"
if [ "$1" == "service" ]; then
# setup the named pipe
rm "$pipe"
mkfifo "$pipe"
# start watching for requests
while true
do
# watch the pipe for trigger events requesting lock screen status
read request < "$pipe"
# respond across the same pipe wit the current lock screen status
gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked | grep -oP "(true)|(false)" > "$pipe"
done
else
# make sure the pipe exists
if [ ! -e "$pipe" ]; then
echo "This script must started in service mode before lock status can be queried."
exit
fi
# send a request for screen lock status and read the response
touch "$pipe"
read status < "$pipe"
[ "$status" == "" ] && status="This script must started in service mode before lock status can be queried."
# print reponse to screen for use by calling application
echo $status
fi
如 cmets 中所述,您需要以两种方式调用此脚本。当您的用户登录时,以服务模式启动此脚本。我使用“启动应用程序”程序来调用脚本,但它的调用方式并不重要,只要它在登录时由您的用户帐户调用即可。 然后在您的用户服务中,只需调用此脚本,如果屏幕被锁定,它将返回“true”,如果屏幕被解锁,它将返回“false”。
【讨论】:
以上是关于如何从 systemd 用户服务访问会话 D-Bus?的主要内容,如果未能解决你的问题,请参考以下文章
如何从 _app.js 服务器端全局访问下一个身份验证用户会话数据?
在 WSL2 openSUSE-Leap-15.2 环境中,为 xrdp 和 systemd-modules-load / auditd 正确设置 sudoers 用户/会话失败