Bashツールを使用すると、Claudeが永続的なbashセッションでシェルコマンドを実行でき、システム操作、スクリプト実行、コマンドライン自動化が可能になります。
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はコマンドをチェーンして複雑なタスクを完了できます:
# ユーザーリクエスト
"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 outputClaudeのツール呼び出しの処理
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, NoneBashツールを実装する際、さまざまなエラーシナリオを処理します:
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?