PreToolUse hook que intercepta y bloquea comandos Bash peligrosos antes de ejecutarlos.
# Archivo: .claude/hooks/validate-bash.py
# Evento: PreToolUse (matcher: Bash)
#!/usr/bin/env python3
import json
import sys
import re
BLOCKED_PATTERNS = [
(r"\brm\s+-rf\s+/", "Bloqueado: rm -rf / es destructivo"),
(r"\bsudo\s+rm", "Bloqueado: sudo rm requiere confirmación manual"),
(r"DROP\s+TABLE", "Bloqueado: DROP TABLE sin backup verificado"),
(r"truncate\s+", "Bloqueado: TRUNCATE requiere confirmación manual"),
(r"git\s+push\s+--force\s+.*main", "Bloqueado: force push a main no permitido"),
]
def main():
input_data = json.load(sys.stdin)
if input_data.get("tool_name") != "Bash":
sys.exit(0)
command = input_data.get("tool_input", {}).get("command", "")
for pattern, message in BLOCKED_PATTERNS:
if re.search(pattern, command, re.IGNORECASE):
print(message, file=sys.stderr)
sys.exit(2) # exit 2 = error bloqueante
sys.exit(0)
if __name__ == "__main__":
main()
# ── Configurar en .claude/settings.json ──
# {
# "hooks": {
# "PreToolUse": [{
# "matcher": "Bash",
# "hooks": [{ "type": "command",
# "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py\"" }]
# }]
# }
# }Example output
Claude intenta ejecutar: rm -rf /tmp/cache Hook intercepta → "Bloqueado: rm -rf / es destructivo" Claude recibe error y propone alternativa más segura