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 | 아니오 | bash 세션을 다시 시작하려면 true로 설정 |
*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는 두 개의 별도 실행 환경에 접근할 수 있습니다: 로컬 bash 세션과 Anthropic의 샌드박스 컨테이너입니다. 상태는 이들 간에 공유되지 않습니다. 환경을 구분하도록 Claude에 프롬프트하는 방법에 대한 지침은 다른 실행 도구와 함께 코드 실행 사용을 참조하세요.
Was this page helpful?