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-sonnet-4-5",
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):
# 將命令發送到 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
}實現安全措施
添加驗證和限制:
def validate_command(command):
# 阻止危險命令
dangerous_patterns = ['rm -rf /', 'format', ':(){:|:&};:']
for pattern in dangerous_patterns:
if pattern in command:
return False, f"Command contains dangerous pattern: {pattern}"
# 根據需要添加更多驗證
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 工具與文本編輯器和其他工具結合時最強大。