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

如何以root进程身份在所有已登录会话中启停Launch Agent?

解决macOS下以Root身份启停所有已登录用户的Launch Agent

核心原理

Launch Agent是与用户会话绑定的,Root直接执行launchctl只会操作Root自身的会话,无法覆盖普通用户的登录会话。要实现所有已登录用户的Agent立即启停,需要切换到每个用户的UID上下文,在对应会话中执行Launchctl命令。

安装时:加载所有已登录用户的Launch Agent

以下脚本可在Root/管理员权限下运行,自动适配不同macOS版本:

# 获取所有已登录的非Root用户
LOGGED_IN_USERS=$(who | awk '{print $1}' | sort -u)

for USER in $LOGGED_IN_USERS; do
    USER_UID=$(id -u "$USER")
    # 跳过Root用户
    if [ "$USER_UID" -ne 0 ]; then
        # 检测macOS大版本
        OS_MAJOR_VERSION=$(sw_vers -productVersion | awk -F '.' '{print $1}')
        if [ "$OS_MAJOR_VERSION" -ge 11 ]; then
            # Big Sur及以上版本使用bootstrap命令
            launchctl asuser "$USER_UID" launchctl bootstrap gui/"$USER_UID" /Library/LaunchAgents/com.example.MyAgent.plist
        else
            # Catalina及以下版本使用load命令
            launchctl asuser "$USER_UID" launchctl load /Library/LaunchAgents/com.example.MyAgent.plist
        fi
    fi
done

卸载时:停止所有已登录用户的Launch Agent

对应卸载脚本如下:

# 获取所有已登录的非Root用户
LOGGED_IN_USERS=$(who | awk '{print $1}' | sort -u)

for USER in $LOGGED_IN_USERS; do
    USER_UID=$(id -u "$USER")
    # 跳过Root用户
    if [ "$USER_UID" -ne 0 ]; then
        # 检测macOS大版本
        OS_MAJOR_VERSION=$(sw_vers -productVersion | awk -F '.' '{print $1}')
        if [ "$OS_MAJOR_VERSION" -ge 11 ]; then
            # Big Sur及以上版本使用bootout命令
            launchctl asuser "$USER_UID" launchctl bootout gui/"$USER_UID" /Library/LaunchAgents/com.example.MyAgent.plist
        else
            # Catalina及以下版本使用unload命令
            launchctl asuser "$USER_UID" launchctl unload /Library/LaunchAgents/com.example.MyAgent.plist
        fi
    fi
done

关键注意事项

  • 权限配置:确保/Library/LaunchAgents/com.example.MyAgent.plist的权限为root:wheel,权限值设为644,否则用户会话无法正常加载Agent:
    chown root:wheel /Library/LaunchAgents/com.example.MyAgent.plist
    chmod 644 /Library/LaunchAgents/com.example.MyAgent.plist
    
  • 后续登录用户:由于plist放在/Library/LaunchAgents且RunAtLoad=true,后续登录的用户会自动加载Agent,无需重复执行上述脚本。
  • 权限要求:launchctl asuser命令必须以Root/管理员权限执行,你的安装程序权限正好满足这个要求。

内容的提问来源于stack exchange,提问作者c00000fd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:45:30