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

AppleScript在终端正常运行,crontab触发时失效的问题排查

问题:Crontab触发AppleScript时无法读取钥匙串密码,仅能激活SelfControl应用

我写了一段用于调度SelfControl应用的AppleScript脚本,终端直接运行完全正常,但通过crontab定时触发时,只能完成激活SelfControl的步骤,后续流程卡壳。补充日志后发现,问题出在读取钥匙串密码的代码行,报错信息为:

execution error: security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain. (44)

脚本内容

tell application "SelfControl" to activate

set myPass to do shell script "security find-generic-password -w -s 'My Test' -a 'account_dummy'"

tell application "System Events"
    delay 0.5
    tell process "SelfControl"
        delay 0.5
        tell slider of window "SelfControl" to set value to 1.0
        delay 0.5
        click button "Start Block" of window "SelfControl"
    end tell
    delay 0.5
    repeat while exists (processes where name is "SecurityAgent")
        delay 0.5
        tell process "SecurityAgent"
            
            set frontmost to true
            if (count of windows) > 0 then
                set window_name to name of front window
            end if
            try
                keystroke myPass
                delay 0.1
                keystroke return
                delay 0.1
            on error
                -- do nothing to skip the error
            end try
        end tell
        delay 0.5
    end repeat
end tell

Crontab配置

*/5 14-23 * * 1,2,3,4,5 osascript /Users/cristobal/Library/Mobile\ Documents/com~apple~ScriptEditor2/Documents/selfcontrol.scpt

当前每5分钟运行一次是测试设置,拦截时长暂设为1分钟,问题解决后会调整参数。


解决方案

1. 显式指定钥匙串路径

crontab运行在非交互式环境下,默认可能找不到用户的登录钥匙串,需在security命令中明确指定路径:
修改读取密码的代码行:

set myPass to do shell script "security find-generic-password -w -s 'My Test' -a 'account_dummy' -k ~/Library/Keychains/login.keychain-db"

2. 授予权限访问钥匙串

  • 打开「系统设置」→「隐私与安全性」→「完整磁盘访问」,添加/usr/sbin/cron程序;
  • 打开「钥匙串访问」,找到"My Test"密码项,右键「显示简介」→「访问控制」,添加cron和osascript程序,允许它们访问该密码。

3. 用环境变量指定钥匙串

在crontab配置中添加环境变量,明确钥匙串位置:

*/5 14-23 * * 1,2,3,4,5 export KEYCHAIN=~/Library/Keychains/login.keychain-db && osascript /Users/cristobal/Library/Mobile\ Documents/com~apple~ScriptEditor2/Documents/selfcontrol.scpt

4. 更优替代:使用SelfControl命令行工具

SelfControl自带命令行接口,无需模拟GUI操作,更适合定时任务:
直接在crontab中执行(替换拦截时长和黑名单路径):

*/5 14-23 * * 1,2,3,4,5 /Applications/SelfControl.app/Contents/MacOS/SelfControl --block 60 --blacklist ~/.selfcontrol_blocklist

这种方式不需要读取钥匙串,也不会有GUI模拟的稳定性问题。


内容的提问来源于stack exchange,提问作者Cristóbal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:55:15