rootでユーザーに通知するために通知を送信する方法は? [コピー]

rootでユーザーに通知するために通知を送信する方法は? [コピー]
#!/bin/bash
export DISPLAY=:0
state=$(upower -i $(upower -e | grep BAT) | grep --color=never -E "state" )
stat=${state:25:32}
batperct=$(upower -i $(upower -e | grep '/battery') | grep  -E "percentage:")
bat=${batperct:24:26}
intbat=$(echo $bat | cut -d'%' -f1)
if [ "$intbat" -lt "15" -a "$stat" == "discharging" ]; then
    notify-send 'battery low..! please plugin charger..... charge is only' "$intbat"    
fi  

一般ユーザー()として実行すると、スクリプトが正しく実行されますbash script.sh。デスクトップ通知が表示されます。

root実行するとsudo bash script.shデスクトップ通知が表示されますいいえ見せる

rootで通知を送信してユーザーに通知するにはどうすればよいですか?

私はアーチLinuxを使用しています。

ベストアンサー1

このコマンドをnotify-send使用するには、環境変数を設定し、DBUS_SESSION_BUS_ADDRESSセッションバスを所有しているユーザーとして呼び出す必要があります。

次のスクリプトでは、関数はnotify_usersセッションバスを制御するすべてのdbusデーモンを検索します。そのデーモンのコマンドラインは次のとおりです。

dbus-daemon --fork --session --address=unix:abstract=/tmp/dbus-ceVHx19Kiy

このプロセスのために、所有者とdbusアドレスが決定されます。その後、使用できますnotify-send。このスクリプトは、GDMセッションを使用してログインしたすべてのユーザーに通知する必要があります。しかし、私は一度もテストしたことがありません。

注:root以外のユーザーと呼ばれる場合sudo

#!/bin/bash

# Inform all logged on users
# Usage: notify_users TITLE MESSAGE [urgency [icon]]
notify_users()
{
    typeset title="$1"
    typeset message="$2"
    typeset urgency="${3:-critical}"
    typeset icon="${4:-}"

    case "$urgency" in
        "low") : ;;
        "normal") : ;;
        "critical") : ;;
        *)
            urgency="normal"
            ;;
    esac

    typeset ls user bus_addr

    typeset IFS=$'\n'

    # for all dbus-daemon processes that create a session bus
    for ln in "$(ps -eo user,args | grep "dbus-daemon.*--session.*--address=" | grep -v grep)"; do
        # get the user name
        user="$(echo "$ln" | cut -d' ' -f 1)"
        # get dbus address
        bus_addr="$(echo "$ln" | sed 's/^.*--address=//;s/ .*$//')"
        # run notify-send with the correct user
        DBUS_SESSION_BUS_ADDRESS="$bus_addr" sudo -u $user -E /usr/bin/notify-send -u "$urgency" -i "$icon" "$title" "$message"
    done
}

state="$(upower -i $(upower -e | grep BAT))"

# if the state contains the word "discharging"
if [[ "$state" = *discharging* ]]; then

    perc=$(echo "$state" | grep "percentage" | awk '{print $2}' | tr -d '%')

    icon="$(echo "$state" | grep "icon-name:" | awk '{print $2}' | tr -d "'\"" )"

    if [ "$perc" -lt 15 ]; then
        notify_users "Battery Low!"  "Please plugin charger ... charge is only $perc%" "critical" "$icon"
    fi
fi

おすすめ記事