MacOS下cron执行脚本无GUI通知问题求助
macOS下cron执行osascript无法弹出GUI通知的解决办法
cron运行在无GUI的系统级环境中,不会关联当前用户的桌面会话,这就是单独运行脚本正常、但cron执行时通知不显示的核心原因。要解决这个问题,需要让osascript在当前登录用户的GUI会话环境下执行,具体修改如下:
修改后的脚本代码
# 获取当前控制台登录的用户 CURRENT_USER=$(stat -f "%Su" /dev/console) # 获取该用户的UID USER_UID=$(id -u "$CURRENT_USER") if [ "$(defaults read /Library/Preferences/SystemConfiguration/com.apple.nat | grep -i Enabled | sed -e 's/.*0/0/g' | sed 's/.$//')" != 0 ]; then defaults write /Library/Preferences/SystemConfiguration/com.apple.nat NAT -dict Enabled -int 0 # 以当前登录用户的身份执行osascript,确保GUI环境可用 launchctl asuser "$USER_UID" sudo -u "$CURRENT_USER" osascript -e 'display notification "Internet Sharing disabled" with title "Attention!" sound name "Ping"' # 修正原脚本中的拼写错误:Interen → Internet echo "Attempted to disable Internet Sharing on host $(hostname)" | mail -s "Alert" name@domain.com fi
关键说明
stat -f "%Su" /dev/console:获取当前在控制台登录的活跃用户,确保命令在正确的用户会话中运行launchctl asuser "$USER_UID":指定以目标用户的UID执行后续命令,让osascript能访问到用户的GUI会话- 原脚本中存在拼写错误
Interen Sharing,已修正为Internet Sharing
内容的提问来源于stack exchange,提问作者B0n3s
相关产品推荐
相关产品推荐

