이 기능은 Zero Data Retention (ZDR)의 적용 대상입니다. 조직에 ZDR 계약이 체결되어 있는 경우, 이 기능을 통해 전송된 데이터는 API 응답이 반환된 후 저장되지 않습니다.
Bash 도구는 Claude가 지속적인 bash 세션에서 셸 명령어를 실행할 수 있게 하여 시스템 작업, 스크립트 실행 및 명령줄 자동화를 가능하게 합니다. 셸 접근은 기본적인 에이전트 기능입니다. 셸 전용 검증을 사용하여 실제 터미널 작업을 평가하는 벤치마크인 Terminal-Bench 2.0에서 Claude는 지속적인 bash 세션에 접근할 때 강력한 성능 향상을 보여줍니다.
Bash 도구는 Claude에게 다음을 제공합니다:
모델 지원에 대해서는 도구 참조를 참조하세요.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
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 | 아니요 | bash 세션을 재시작하려면 true로 설정 |
*restart를 사용하지 않는 경우 필수
Claude는 명령어를 연결하여 복잡한 작업을 완료할 수 있습니다:
User request:
"Install the requests library and create a simple Python script that
fetches a joke from an API, then run it."
Claude's tool uses:
1. Install package
{"command": "pip install requests"}
2. Create script
{"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. Run script
{"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, NoneBash 도구를 구현할 때 다양한 오류 시나리오를 처리하세요:
Bash 도구는 직접적인 시스템 접근을 제공합니다. 다음과 같은 필수 안전 조치를 구현하세요:
ulimit를 사용하여 리소스 제약 설정sudo, rm -rf 등)bash 도구는 API 호출에 245개의 입력 토큰을 추가합니다.
다음 항목에 의해 추가 토큰이 소비됩니다:
전체 가격 세부 정보는 도구 사용 가격을 참조하세요.
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가 환경을 구분하도록 프롬프트하는 방법에 대한 지침은 다른 실행 도구와 함께 코드 실행 사용하기를 참조하세요.
Was this page helpful?
이 검사는 첫 번째 방어선입니다. 더 강력한 격리를 위해서는 검증된 명령어를 shell=False로 실행하고 shlex.split(command)를 인수 목록으로 전달하여 셸이 문자열을 해석하지 않도록 하세요.