Mac OS Ventura创建LaunchAgent plist触发通知的原因与解决方法
问题解答
为什么会触发通知?
macOS Ventura 13.5的TCC(Transparency, Consent, and Control)安全框架会监控~/Library/LaunchAgents目录的文件写入操作。当未经过系统认可的程序(比如未签名的Python脚本)直接向该目录写入plist文件时,系统会判定这是潜在的未授权后台项添加,从而触发“Background Items Added”通知。
而Chrome、Homebrew这类程序不会触发通知的原因主要有两点:
- 它们的核心程序是经过Apple公证/签名的,系统信任其操作合法性;
- 它们不会直接写入plist文件,而是通过
launchctl的官方接口(如bootstrap/enable)或系统LaunchServices API来注册后台任务,这类操作会被TCC框架视为合法授权行为。
如何实现无通知的plist程序化创建?
可以通过以下几种方式解决:
1. 对Python脚本进行代码签名
用Apple Developer ID对你的Python脚本进行签名,让系统认可其操作权限:
# 假设你的脚本名为create_launch_agent.py codesign --sign "Developer ID Application: Your Name (XXXXXX)" create_launch_agent.py
签名后的脚本写入plist文件时,TCC会判定为可信操作,不会触发通知。
2. 使用launchctl官方接口管理plist
不要直接写入~/Library/LaunchAgents目录,而是先在临时目录生成plist,再通过launchctl命令完成注册:
import plistlib import os import subprocess # 临时目录生成plist temp_plist_path = "/tmp/com.your.agent.plist" plist_data = { "Label": "com.your.agent", "ProgramArguments": ["/usr/bin/python3", "/path/to/your/script.py"], "RunAtLoad": True } with open(temp_plist_path, 'wb') as f: plistlib.dump(plist_data, f) # 使用launchctl bootstrap注册 user_id = os.getuid() subprocess.run([ "launchctl", "bootstrap", f"gui/{user_id}", temp_plist_path ], check=True) # 可选:删除临时文件 os.remove(temp_plist_path)
这种方式通过系统官方命令注册后台任务,不会触发通知。
3. 利用PyObjC调用系统LaunchServices API
通过PyObjC绑定调用macOS原生API来注册LaunchAgent,这种方式完全符合系统规范:
import plistlib import os from Foundation import NSURL, LSRegisterURL plist_path = os.path.expanduser("~/Library/LaunchAgents/com.your.agent.plist") # 先生成plist文件 plist_data = { "Label": "com.your.agent", "ProgramArguments": ["/usr/bin/python3", "/path/to/your/script.py"], "RunAtLoad": True } with open(plist_path, 'wb') as f: plistlib.dump(plist_data, f) # 调用LSRegisterURL注册 url = NSURL.fileURLWithPath_(plist_path) LSRegisterURL(url, True)
这种方式会让系统正确识别后台任务的添加,不会弹出通知。
内容的提问来源于stack exchange,提问作者Creative crypter
相关产品推荐
相关产品推荐

