This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.
bash 工具使 Claude 能夠在持久的 bash 會話中執行 shell 命令,允許系統操作、腳本執行和命令行自動化。Shell 訪問是一項基礎代理功能。在 Terminal-Bench 2.0 上,這是一個使用僅 shell 驗證評估真實世界終端任務的基準測試,Claude 在訪問持久 bash 會話時表現出強勁的性能提升。
bash 工具為 Claude 提供:
有關模型支持,請參閱工具參考。
Was this page helpful?
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-7",
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 可以鏈接命令以完成複雜任務:
用戶請求:
"安裝 requests 庫並創建一個簡單的 Python 腳本,
從 API 獲取笑話,然後運行它。"
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 環境
創建一個持久的 bash 會話,Claude 可以與之交互:
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,
}實現安全措施
添加驗證和限制。使用允許列表而不是阻止列表,因為阻止列表容易被繞過。拒絕 shell 操作符,以便鏈接的命令無法繞過允許列表:
import shlex
ALLOWED_COMMANDS = {"ls", "cat", "echo", "pwd", "grep", "find", "wc", "head", "tail"}
SHELL_OPERATORS = {"&&", "||", "|", ";", "&", ">", "<", ">>"}
def validate_command(command):
# Allow only commands from an explicit allowlist
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"
# Reject shell operators that would chain additional commands
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實現 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"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 區分環境的指導,請參閱將代碼執行與其他執行工具結合使用。
此檢查是第一道防線。為了更強的隔離,使用 shell=False 運行驗證的命令,並將 shlex.split(command) 作為參數列表傳遞,這樣 shell 永遠不會解釋該字符串。