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

macOS通过LaunchAgent运行命令行截屏工具无权限弹窗无法截屏求助

解决步骤

1. 先手动触发权限申请

暂时不通过LaunchAgent启动,直接在终端执行一次命令:

/bin/capture

此时会弹出屏幕录制权限请求,点击允许后,进入「系统设置>隐私与安全性>屏幕录制」,确认/bin/capture的权限开关已开启。如果未出现该程序条目,可手动点击加号按钮,选中/bin/capture添加并开启权限。

2. 修改LaunchAgent配置

你当前的plist缺少GUI会话关联配置,需要新增SessionCreate字段,修改后完整配置如下:

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.test.launchagent.screencapture</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/capture</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <!-- 新增以下配置,关联用户GUI会话 -->
    <key>SessionCreate</key>
    <true/>
</dict>
</plist>

修改完成后重新加载服务:

# 卸载旧服务
sudo launchctl unload /Library/LaunchAgents/com.test.launchagent.screencapture.plist
# 加载新配置
sudo launchctl load /Library/LaunchAgents/com.test.launchagent.screencapture.plist

3. 代码层面主动申请权限(可选,建议添加)

在截屏逻辑前新增权限检查与主动申请代码,适配 macOS 10.15+ 权限机制:

#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import <CoreGraphics/CoreGraphics.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"capture screen...");
        // 新增权限检查逻辑
        if (@available(macOS 10.15, *)) {
            BOOL hasAccess = CGPreflightScreenCaptureAccess();
            if (!hasAccess) {
                CGRequestScreenCaptureAccess();
                // 首次申请权限用户同意后,下次启动即可正常截屏
                return 0;
            }
        }
        CGRect mainRect = CGDisplayBounds(CGMainDisplayID());
        CGImageRef desktopImage = CGWindowListCreateImage(mainRect, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageBestResolution | kCGWindowImageShouldBeOpaque);
        NSBitmapImageRep *bmpImgRef = [[NSBitmapImageRep alloc] initWithCGImage:desktopImage];
        NSData *data = [bmpImgRef representationUsingType:NSBitmapImageFileTypeJPEG properties:@{NSImageCompressionFactor: @(1)}];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        [fmt setDateFormat:@"yyyyMMdd_hh:mm:ss"];
        [data writeToURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"/tmp/%@.jpg", [fmt stringFromDate:[NSDate date]]]] atomically:true];
    }
    return 0;
}

额外建议

不建议将自定义二进制放在/bin目录,该目录受macOS系统完整性保护(SIP)限制,仅系统进程可写入,建议将工具移至/usr/local/bin/目录,同步修改plist内的执行路径即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:54:02