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セッションでシェルコマンドを実行でき、システム操作、スクリプト実行、コマンドラインの自動化が可能になります。シェルアクセスはエージェント機能の基礎です。シェルのみの検証を使用して実世界のターミナルタスクを評価するベンチマークであるTerminal-Bench 2.0では、Claudeは永続的なbashセッションへのアクセスにより強いパフォーマンス向上を示しています。
Bashツールは、Claudeに以下を提供します:
モデルサポートについては、ツールリファレンスを参照してください。
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ライブラリをインストールして、APIからジョークを取得する
シンプルなPythonスクリプトを作成し、実行してください。」
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,
}セキュリティ対策を実装
検証と制限を追加します。ブロックリストはバイパスが容易なため、許可リストを使用します。チェーンされたコマンドが許可リストを通過できないようにシェルオペレータを拒否します:
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"
# 追加コマンドをチェーンするシェルオペレータを拒否
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)を引数リストとして渡します。これにより、シェルが文字列を解釈することはありません。
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は2つの別々の実行環境にアクセスできます:ローカルbashセッションとAnthropicのサンドボックスコンテナです。状態はそれらの間で共有されません。他の実行ツールでコード実行を使用するを参照して、Claudeに環境を区別するよう促すガイダンスを確認してください。
Was this page helpful?