十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

如何用 sandbox-exec 为 macOS Computer Use Agent 实现带沙箱的 bash 与 python 执行?

如何用 sandbox-exec 为 macOS Computer Use Agent 实现带沙箱的 bash 与 python 执行? 如何用 sandbox-exec 为 macOS Computer Use Agent 实现带沙箱的 bash 与 python 执行【免费下载链接】claude-quickstartsA collection of projects designed to help developers quickly get started with building deployable applications using the Claude API项目地址: https://gitcode.com/GitHub_Trending/an/claude-quickstarts在 claude-quickstarts 仓库的computer-use-best-practices参考实现中Computer Use Agent 除了控制鼠标键盘和浏览器还提供bash与python两个执行类工具。如果你的目标是让模型能跑 shell 命令和 Python 脚本又不希望它读取本机凭据、向任意位置写文件或访问网络这篇项目就用 macOS 自带的sandbox-exec加一份 SBPL 策略文件完成了这件事你可以直接照着阅读、运行和验证。适用前提这套机制只在 macOS 上工作——README 明确说明sandbox-exec是关键 Mac 依赖Linux 变体不在范围内运行环境需要 Python 3.11macOS 自带的python3是 3.9不可用。沙箱实现由哪几个文件构成实现分散在三个文件里读代码时按这个顺序看shell.py ——BashTool与PythonTool的实现负责把模型给的命令包装进sandbox-exec执行default.sb —— sandbox-exec 的策略文件SBPL 语法定义允许/拒绝的规则constants.py ——SANDBOX_PROFILE REPO_ROOT / sandbox / default.sb指定策略文件路径同文件中的max_shell_output_bytes: int 64 * 1024constants.py#L137限制捕获输出的字节数。核心执行逻辑在_run_sandboxed()shell.py#L28-L51。模型提交一段脚本后工具先把它写成临时脚本文件bash 用.sh后缀交给/bin/bashpython 用.py后缀交给当前解释器sys.executable然后拼出如下命令执行sandbox-exec -f SANDBOX_PROFILE -D SCRATCH本次调用的 scratch 目录 -D HOME用户主目录 解释器 脚本路径对应源码中的命令构造cmd [ sandbox-exec, -f, str(SANDBOX_PROFILE), -D, fSCRATCH{scratch}, -D, fHOME{Path.home()}, *argv, ] proc subprocess.Popen(cmd, stdoutsubprocess.PIPE, stderrsubprocess.STDOUT, cwdscratch)-D SCRATCH与-D HOME是传给策略文件的 SBPL 参数策略里用(param SCRATCH)、(param HOME)引用它们这样同一份.sb文件不需要硬编码路径就能复用到每次调用。进程的工作目录cwd就是 scratch 目录stdout 与 stderr 合并捕获。scratch 目录有两种来源见 shell.py#L76-L102Agent 正常跑任务时复用runs/timestamp/scratch/脚本状态在整个 run 内跨工具调用保留单独调用工具无 per-run 目录时每次调用各拿一个全新临时目录用完即弃。默认策略广泛可读只能写 scratch禁止联网default.sb 全文很短规则如下;; sandbox-exec profile for the bash/python tools. ;; ;; Policy: read anywhere *except* known credential locations, write only to the ;; per-call SCRATCH directory, no network. The interesting boundaries for a ;; demo are write- and network-denial; trying to enumerate every readable ;; system path makes the profile brittle without adding much, so we allow ;; file-read* broadly and then deny the secret paths below (later rules take ;; precedence in SBPL). (version 1) (deny default) (import /System/Library/Sandbox/Profiles/bsd.sb) (deny network*) (allow process-exec) (allow process-fork) (allow signal) (allow sysctl-read) (allow mach-lookup) (allow file-read*) (allow file-write* (subpath (param SCRATCH)) (subpath /dev)) (deny file-read* (subpath (string-append (param HOME) /.ssh)) (subpath (string-append (param HOME) /.aws)) (subpath (string-append (param HOME) /.gnupg)) (subpath (string-append (param HOME) /.config/gcloud)) (subpath (string-append (param HOME) /.kube)) (subpath (string-append (param HOME) /.docker)) (subpath (param HOME) /.config/gh)) (literal (string-append (param HOME) /.netrc)) (regex #/\.env$) (regex #/\.env\.) )各段的含义按文件自身注释和规则顺序理解(deny default)加上导入系统基础策略bsd.sb整体基调是拒绝再逐条放开必需能力进程执行/派生、信号、sysctl-read、mach-lookup否则连解释器都跑不起来。(deny network*)拒绝一切网络访问。(allow file-read*)允许广泛读文件。文件头注释解释了取舍逐个枚举可读取的系统路径会让 profile 脆弱且收益不大所以读放开、写收紧再在末尾用 deny 规则挡掉凭据位置。(allow file-write* ...)只允许写入两个子路径SCRATCH目录和/dev。其余位置写文件会被拒。最后的(deny file-read* ...)列出不可读的凭据位置~/.ssh、~/.aws、~/.gnupg、~/.config/gcloud、~/.kube、~/.docker、~/.config/gh、~/.netrc以及任何文件名匹配/\.env$或/\.env\.即.env、.env.local这类的文件。一个关键细节SBPL 中后面的规则优先。所以读是「先广泛 allow再对凭据路径 deny」调整策略时新增的 deny 规则必须放在对应 allow 之后才生效。准备环境按 README 的安装部分准备。在computer-use-best-practices目录内执行# 先把 python3.13 替换成你实际安装的 3.11 解释器 python3.13 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -r requirements.txt # 为 browser 工具下载 headless Chromium一次性约 150 MB python -m playwright install chromiumREADME 注明 Chromium 下载只服务于browser工具本文只关心bash/python沙箱但按 README 主路径一并装上可以避免缺依赖。然后设置 API keycp .env.example .env # then edit .env # or: export ANTHROPIC_API_KEY...另外让 Agent 完整跑起来还需要在 System Settings → Privacy Security 给终端授予 Screen Recording 和 Accessibility 权限然后完全退出并重开终端首次运行时 preflight 会自动打开对应设置面板。macOS 15Sequoia及以上还会在首次截屏时额外弹出一个系统级确认框点 Allow 即可。验证沙箱是否生效有三条验证路径从不需要模型交互的到完整 Agent 运行。1. 用 tool panel 手工触发 bash / python最快README 的 Tool panel 小节提供了一个不经过模型、直接手工执行任意工具的页面python -m uvicorn dev_ui.tool_panel.server:app --reload # open http://127.0.0.1:8000打开 http://127.0.0.1:8000每个工具有一张按其input_schema自动生成的表单bash表单的字段是commandpython表单的字段是code见 shell.py。可以设置一个倒计时延迟再点 Run结果面板显示返回的 JSON。用这种方式验证正常命令如echo hello能返回输出而写入 home 目录或读取.env类文件的命令按策略会被拒。2. 跑仓库自带的沙箱测试tests/test_shell.py 专门覆盖了这两个工具全部标注darwin_only非 macOS 平台自动跳过因为sandbox-exec是 macOS 的。在虚拟环境中执行python -m pytest其中与沙箱直接相关的用例和判定用例操作预期test_bash_echoecho hello非错误输出包含hellotest_python_printprint(1 1)非错误输出以2开头test_sandbox_denies_home_writetouch ~/should_not_exist_cu_demores.is_error为真写 home 被拒test_sandbox_denies_secret_readls ~/.ssh、cat 某个 .env 文件均报错若本机~/.ssh不存在或为空该用例会跳过test_output_truncatedprint(x * 200_000)输出长度不超过cfg.max_shell_output_bytes 100且包含[output truncated标记这组测试同时验证了「正常执行能跑通」和「策略拒绝真的发生」两个方向。3. 完整 Agent 运行中观察python -m computer_use 自然语言任务任务输入是自由文本例如可以写一句明确要求模型使用 bash 工具执行命令的任务示例任务按你的需求替换。每次运行会把完整 transcript 写入runs/timestamp/trajectory.py其中transcript.jsonl记录了每次工具调用与结果scratch/子目录就是沙箱允许写入的工作区bash/python/editor三个工具共享它。事后可以用python -m streamlit run dev_ui/trajectory_viewer/app.py在浏览器里回放整段轨迹确认模型调用bash/python时哪些操作被放行、哪些报错。调整策略与参数shell.py 的模块 docstring 给出的定制入口就是一句话「Edit the .sb file to loosen.」即直接编辑 default.sb。修改时的注意事项新增 deny 规则要放在文件靠后的位置——SBPL 是后面的规则优先引用路径用(param SCRATCH)/(param HOME)而不是硬编码这两个参数由_run_sandboxed()的-D标志每次调用注入想收紧读范围时注意文件头注释说明的取舍项目认为逐条枚举可读系统路径会让 profile 脆弱且「不加什么价值」默认策略因此保持广泛可读。输出上限与超时是另外两个边界参数输出上限默认 64 KiBcfg.max_shell_output_bytes 64 * 1024constants.py#L137。stdout/stderr 合并计数超过上限即杀掉进程并在末尾追加[output truncated at 65536 bytes]数值随配置变化。README 的 Configuration 小节说明所有Config字段都可以用CU_FIELD_NAMEvalue环境变量覆盖因此这个上限对应的变量名是CU_MAX_SHELL_OUTPUT_BYTES。30 秒超时硬编码在 shell.py#L25 的_TIMEOUT_S 30不是Config字段超时返回timed out after 30s错误。要改只能改代码。边界与限制平台整套沙箱只在 macOS 上生效。tests/test_shell.py用pytest.mark.skipif(sys.platform ! darwin)标注原因写明「sandbox-exec is macOS」。覆盖范围沙箱只包住bash与python两个工具。computer工具鼠标、键盘、截屏本身不受这份策略约束README 顶部的 CAUTION 仍然强烈建议把整个 Agent 跑在一次性 macOS 虚拟机里README 提到 UTM 与 Parallels 都支持 macOS 客户机。策略边界无网络写仅限 scratch 目录与/dev凭据路径~/.ssh、~/.aws、~/.gnupg、~/.config/gcloud、~/.kube、~/.docker、~/.config/gh、~/.netrc、.env*文件不可读其余读操作放行。执行边界30 秒超时、64 KiB 输出上限、工作目录固定在 scratchbash 脚本在调用结束后会从磁盘删除script.unlink(missing_okTrue)。【免费下载链接】claude-quickstartsA collection of projects designed to help developers quickly get started with building deployable applications using the Claude API项目地址: https://gitcode.com/GitHub_Trending/an/claude-quickstarts创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表