루트로 사용자에게 알리기 위해 통지 보내기를 사용하는 방법은 무엇입니까? [복사]

루트로 사용자에게 알리기 위해 통지 보내기를 사용하는 방법은 무엇입니까? [복사]
#!/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바탕화면 알림이 뜹니다아니요보여주다.

루트로 알림 보내기를 사용하여 사용자에게 알리려면 어떻게 해야 합니까?

저는 아치 리눅스를 사용하고 있습니다.

답변1

이 명령을 notify-send사용하려면 환경 변수를 설정해야 하며 DBUS_SESSION_BUS_ADDRESS세션 버스를 소유한 사용자로 호출해야 합니다.

다음 스크립트에서 함수는 notify_users세션 버스를 제어하는 ​​모든 dbus 데몬을 검색합니다. 해당 데몬의 명령줄은 다음과 같습니다.

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

이 과정을 위해 소유자와 dbus 주소가 결정됩니다. 그런 다음 을 사용할 수 있습니다 notify-send. 이 스크립트는 GDM 세션을 사용하여 로그인한 모든 사용자에게 알려야 합니다. 하지만 저는 한번도 테스트해본 적이 없습니다.

참고: 루트가 아닌 사용자라고 지칭할 경우 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

관련 정보