You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 02:36:23