linuxnotificationsrootdbusnotify

Running notify-send as root


I am trying to get a notification when pluging in a USB device, for this I use a udev rule to track the moment it is pluged and from there I launch a script. The idea on the script was to use what it is explained in the link.

but when trying this:

pids=`pgrep -u $user gnome-panel`

I found that gnome-panel is not there. Googled this work arround and I found quite few people complaining that this work arround is no longer working. So I did a bit of research on the subject and came up with this (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

to get the DBUS_SESSION_BUS_ADDRESS before switching user to a non root user. This statement, if I am not wrong works, so based on the code from the link above I made this other script (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"

For what I can see on the other code, the only problem was getting the DBUS_SESSION_BUS_ADDRESS, and if I am not wrong, with this I can have it.

So my question is, why there isn't a fancy pop-up message on my screen when launching?

sudo sh notify-plugin2.sh

Solution

  • Combining tomy's answer with hongo's answer to another question elegantly solves the issue for me.

    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 "$@"
    }
    

    That function can be used as-is in any script running as root, as a drop-in replacement for the notify-send command.