Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Bash 工具使 Claude 能够在持久化的 bash 会话中执行 shell 命令,支持系统操作、脚本执行和命令行自动化。
Bash 工具为 Claude 提供:
| 模型 | 工具版本 |
|---|---|
| Claude 4 模型和 Sonnet 3.7(已弃用) | bash_20250124 |
旧版工具不保证与新模型向后兼容。请始终使用与您的模型版本对应的工具版本。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
tools=[
{
"type": "bash_20250124",
"name": "bash"
}
],
messages=[
{"role": "user", "content": "List all Python files in the current directory."}
]
)Bash 工具维护一个持久化会话:
| 参数 | 是否必需 | 描述 |
|---|---|---|
command | 是* | 要运行的 bash 命令 |
restart | 否 | 设置为 true 以重启 bash 会话 |
*除非使用 restart,否则为必需参数
Claude 可以链接命令来完成复杂任务:
# 用户请求
"Install the requests library and create a simple Python script that fetches a joke from an API, then run it."
# Claude 的工具使用:
# 1. 安装软件包
{"command": "pip install requests"}
# 2. 创建脚本
{"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. 运行脚本
{"command": "python fetch_joke.py"}会话在命令之间保持状态,因此在步骤 2 中创建的文件在步骤 3 中可用。
Bash 工具作为无模式工具实现。使用此工具时,您不需要像其他工具那样提供输入模式;模式内置于 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):
# Send command to bash
self.process.stdin.write(command + '\n')
self.process.stdin.flush()
# Capture output with timeout
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)
# Return result to Claude
tool_result = {
"type": "tool_result",
"tool_use_id": content.id,
"content": result
}实施安全措施
添加验证和限制:
def validate_command(command):
# Block dangerous commands
dangerous_patterns = ['rm -rf /', 'format', ':(){:|:&};:']
for pattern in dangerous_patterns:
if pattern in command:
return False, f"Command contains dangerous pattern: {pattern}"
# Add more validation as needed
return True, None实现 bash 工具时,需要处理各种错误场景:
Bash 工具提供直接的系统访问。请实施以下基本安全措施:
ulimit 设置资源约束sudo、rm -rf 等)The bash tool adds 245 input tokens to your API calls.
Additional tokens are consumed by:
有关完整定价详情,请参阅工具使用定价。
pytest && coverage reportnpm install && npm run buildgit status && git add . && git commit -m "message"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 工具与文本编辑器及其他工具结合使用时最为强大。
Was this page helpful?