以root身份运行notify-send

Sxu*_*ach 9 linux notifications dbus root notify

我正在尝试在插入USB设备时收到通知,为此我使用udev规则来跟踪它被插入的时刻,然后从那里启动脚本.脚本的想法是使用链接中解释的内容.

但是在尝试这个时:

pids=`pgrep -u $user gnome-panel`
Run Code Online (Sandbox Code Playgroud)

我发现gnome-panel不在那里.用Google搜索这项工作,我发现很少有人抱怨这项工作不再有效.所以我对这个主题进行了一些研究,并想出了这个(notify-plugin2.sh):

#!/bin/bash

DBUS_SESSION_BUS_ADDRESS=$(cat /home/user/.dbus/session-bus/$(cat /var/lib/dbus/machine-id)-0 | grep DBUS_SESSION_BUS_ADDRESS= | sed -e 's/DBUS_SESSION_BUS_ADDRESS=//')

su user Test.sh $DBUS_SESSION_BUS_ADDRESS
Run Code Online (Sandbox Code Playgroud)

DBUS_SESSION_BUS_ADDRESS在将用户切换到非root用户之前获取.这句话,如果我没有错误的作品,那么基于上面链接的代码我做了这个其他的脚本(Test.sh)

#!/bin/sh
user=`whoami`
title="Test"
timeout=30000
icon="~/Pictures/PicturesForPwrPoint/Pluged.jpg"

DBUS_SESSION_BUS_ADDRESS=$1

echo $DBUS_SESSION_BUS_ADDRESS
DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS \ notify-send -u low -t $timeout -i "$icon" "$title"
Run Code Online (Sandbox Code Playgroud)

对于我在其他代码上可以看到的,唯一的问题是获得DBUS_SESSION_BUS_ADDRESS,如果我没有错,我可以拥有它.

所以我的问题是,为什么启动时屏幕上没有花哨的弹出消息?

sudo sh notify-plugin2.sh
Run Code Online (Sandbox Code Playgroud)

tom*_*omy 9

从以 root
身份运行的后台脚本发送桌面通知(分别用运行 X 的用户和用户 ID 替换 X_user 和 X_userid):

sudo -u X_user DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/X_userid/bus notify-send 'Hello world!' 'This is an example notification.'
Run Code Online (Sandbox Code Playgroud)

这取自:https : //wiki.archlinux.org/index.php/Desktop_notifications


Fab*_* A. 7

结合tomy的答案hongo对另一个问题的回答,优雅地解决了我的问题.

function notify-send() {
    #Detect the name of the display in use
    local display=":$(ls /tmp/.X11-unix/* | sed 's#/tmp/.X11-unix/X##' | head -n 1)"

    #Detect the user using such display
    local user=$(who | grep '('$display')' | awk '{print $1}' | head -n 1)

    #Detect the id of the user
    local uid=$(id -u $user)

    sudo -u $user DISPLAY=$display DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus notify-send "$@"
}
Run Code Online (Sandbox Code Playgroud)

该函数可以在任何运行的脚本中按原样使用root,作为notify-send命令的替代品.


dei*_*mus 6

通知服务已更改为ubuntu 14.04.

它现在被称为smth org.freedesktop.Notifications.service

您可以在此处查看有关Notification On Screen Display可能性的更多信息.

您还可以使用以下命令行发送自己的消息

user @ machine~ $ notify-send"消息文本"

只需更新正在启动的脚本udev即可使用它.


解决notify-send以root 身份运行命令所遇到的问题.

尝试运行就像你的普通用户一样,即

su <YOURUSER> -c 'notify-send “Text of message”'
Run Code Online (Sandbox Code Playgroud)