此功能符合零数据保留(ZDR)的条件。当您的组织签订了 ZDR 协议时,通过此功能发送的数据在 API 响应返回后不会被存储。
Bash 工具使 Claude 能够在持久化的 bash 会话中执行 shell 命令,从而实现系统操作、脚本执行和命令行自动化。Shell 访问是一项基础性的智能体能力。在 Terminal-Bench 2.0(一个使用纯 shell 验证来评估真实终端任务的基准测试)中,Claude 在拥有持久化 bash 会话访问权限时表现出显著的性能提升。
Bash 工具为 Claude 提供:
有关模型支持情况,请参阅工具参考。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
tools=[{"type": "bash_20250124", "name": "bash"}],
messages=[
{"role": "user", "content": "List all Python files in the current directory."}
],
)
print(response)Bash 工具维护一个持久化会话:
| 参数 | 必需 | 描述 |
|---|---|---|
command | 是* | 要运行的 bash 命令 |
restart | 否 | 设置为 true 以重启 bash 会话 |
*除非使用 restart,否则为必需
Claude 可以链式调用命令来完成复杂任务:
User request:
"Install the requests library and create a simple Python script that
fetches a joke from an API, then run it."
Claude's tool uses:
1. Install package
{"command": "pip install requests"}
2. Create script
{"command": "cat > fetch_joke.py << 'EOF'\nimport requests\nresponse = requests.get('https://official-joke-api.appspot.com/random_joke')\njoke = response.json()\nprint(f\"Setup: {joke['setup']}\")\nprint(f\"Punchline: {joke['punchline']}\")\nEOF"}
3. Run script
{"command": "python fetch_joke.py"}会话在命令之间保持状态,因此在步骤 2 中创建的文件在步骤 3 中可用。
Bash 工具作为无模式(schema-less)工具实现。使用此工具时,您无需像其他工具那样提供输入模式;该模式已内置于 Claude 的模型中,无法修改。
设置 bash 环境
创建一个 Claude 可以与之交互的持久化 bash 会话:
import subprocess
import threading
import queue
class BashSession:
def __init__(self):
self.process = subprocess.Popen(
["/bin/bash"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=0,
)
self.output_queue = queue.Queue()
self.error_queue = queue.Queue()
self._start_readers()处理命令执行
创建一个函数来执行命令并捕获输出:
def execute_command(self, command):
# 向 bash 发送命令
self.process.stdin.write(command + "\n")
self.process.stdin.flush()
# 在超时限制内捕获输出
output = self._read_output(timeout=10)
return output
处理 Claude 的工具调用
从 Claude 的响应中提取并执行命令:
for content in response.content:
if content.type == "tool_use" and content.name == "bash":
if content.input.get("restart"):
bash_session.restart()
result = "Bash session restarted"
else:
command = content.input.get("command")
result = bash_session.execute_command(command)
# 将结果返回给 Claude
tool_result = {
"type": "tool_result",
"tool_use_id": content.id,
"content": result,
}实施安全措施
添加验证和限制。使用允许列表(allowlist)而非阻止列表(blocklist),因为阻止列表很容易被绕过。拒绝 shell 操作符,以防止链式命令绕过允许列表:
import shlex
ALLOWED_COMMANDS = {"ls", "cat", "echo", "pwd", "grep", "find", "wc", "head", "tail"}
SHELL_OPERATORS = {"&&", "||", "|", ";", "&", ">", "<", ">>"}
def validate_command(command):
# 仅允许明确允许列表中的命令
try:
tokens = shlex.split(command)
except ValueError:
return False, "Could not parse command"
if not tokens:
return False, "Empty command"
executable = tokens[0]
if executable not in ALLOWED_COMMANDS:
return False, f"Command '{executable}' is not in the allowlist"
# 拒绝会串联额外命令的 shell 运算符
for token in tokens[1:]:
if token in SHELL_OPERATORS or token.startswith(("$", "`")):
return False, f"Shell operator '{token}' is not allowed"
return True, None此检查是第一道防线。为了实现更强的隔离,请使用 shell=False 运行已验证的命令,并将 shlex.split(command) 作为参数列表传递,这样 shell 就不会解释该字符串。
在实现 bash 工具时,请处理各种错误场景:
Bash 工具提供直接的系统访问权限。请实施以下基本安全措施:
ulimit 设置资源约束sudo、rm -rf 等)bash 工具会为您的 API 调用增加 245 个输入令牌。
以下内容会消耗额外的令牌:
有关完整的定价详情,请参阅工具使用定价。
pytest && coverage reportnpm install && npm run buildgit status && git add . && git commit -m "message"在长时间运行的智能体工作流中,Git 作为一种结构化的恢复机制,而不仅仅是保存更改的方式:
git log,以了解已完成的工作和接下来的任务。git checkout 回退到最后一个良好的提交,而不是尝试调试损坏的状态。wc -l *.csv && ls -lh *.csvfind . -name "*.py" | xargs grep "pattern"tar -czf backup.tar.gz ./datadf -h && free -mps aux | grep pythonexport PATH=$PATH:/new/path && echo $PATHvim、less 或密码提示Bash 工具与文本编辑器和其他工具结合使用时最为强大。
如果您同时使用代码执行工具,Claude 将可以访问两个独立的执行环境:您的本地 bash 会话和 Anthropic 的沙盒容器。这两个环境之间不共享状态。有关如何提示 Claude 区分不同环境的指导,请参阅将代码执行与其他执行工具结合使用。
Was this page helpful?