![루트로 사용자에게 알리기 위해 통지 보내기를 사용하는 방법은 무엇입니까? [복사]](https://linux55.com/image/145715/%EB%A3%A8%ED%8A%B8%EB%A1%9C%20%EC%82%AC%EC%9A%A9%EC%9E%90%EC%97%90%EA%B2%8C%20%EC%95%8C%EB%A6%AC%EA%B8%B0%20%EC%9C%84%ED%95%B4%20%ED%86%B5%EC%A7%80%20%EB%B3%B4%EB%82%B4%EA%B8%B0%EB%A5%BC%20%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F%20%5B%EB%B3%B5%EC%82%AC%5D.png)
#!/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