我正在尝试使用服务通过带有命令的脚本systemd发送桌面通知。我的脚本如下:.shnotify-sendnotif.sh
#!/bin/bash\nnotify-send "Hello World"\nRun Code Online (Sandbox Code Playgroud)\n我的 systemd 服务notifme.service是下一个:
[Unit]\nDescription=should launch a desktop notification\n\n[Service]\nUser=user\nType=simple\nExecStart=/bin/bash /home/user/notif.sh\nEnvironment="DISPLAY=:0" "XAUTHORITY=/home/user/.Xauthority"\nRun Code Online (Sandbox Code Playgroud)\n当我启动服务时,除了不显示通知之外,一切似乎都运行良好。当我手动运行脚本时,通知脚本可以正常工作。\n当我运行时,systemctl status notifme.service输出为:
\xe2\x97\x8f notifme.service - should launch a desktop notification\n Loaded: loaded (/etc/systemd/system/notifme.service; disabled; vendor preset: enabled)\n Active: active (running) since Sun 2022-02-13 14:39:00 CET; 39s ago\n Main PID: 15771 (bash)\n Tasks: 9 (limit: 18678)\n Memory: 3.5M\n CGroup: /system.slice/notifme.service\n \xe2\x94\x9c\xe2\x94\x8015771 /bin/bash /home/user/notif.sh\n \xe2\x94\x9c\xe2\x94\x8015773 notify-send Hello World\n \xe2\x94\x9c\xe2\x94\x8015780 dbus-launch --autolaunch=017e96ffe51b466384d899f21cbecdc5 --binary-syntax --close-stderr\n …Run Code Online (Sandbox Code Playgroud) 我正在编写一个使用 sudo 权限运行的 python 脚本。在某个时候,我想向用户发送通知。我注意到notify-send不能作为root用户工作,所以我尝试通过执行以实际用户身份运行它su $SUDO_USER -c notify-send ...,但这也不起作用。
以下第一个函数在没有 sudo 权限的情况下运行时有效。当使用 sudo 运行时,它们都不起作用。知道为什么吗?
def notify(message):
subprocess.run(['notify-send', '-i', 'utilities-terminal', 'Notification Title', message],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True)
def notifySudo(message):
subprocess.run(['su', os.environ['SUDO_USER'], '-c', 'notify-send', '-i', 'utilities-terminal', 'Notification Title', message],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True)
Run Code Online (Sandbox Code Playgroud)