A shell allow-list can already keep Claude Code off destructive commands and force-push. It often still leaves sudo. Once the model has root, a "quick fix" can change system packages, rewrite /etc, or install a binary you did not review. A small PreToolUse hook can refuse sudo so the agent stays in the repo.
The hook should name the blocked command and exit 2.
The hook
Save this as .claude/hooks/block_sudo.py and make it executable:
#!/usr/bin/env python3
import json
import re
import sys
try:
event = json.load(sys.stdin)
except json.JSONDecodeError:
sys.exit(0)
tool = event.get("tool_name") or event.get("tool") or ""
inp = event.get("tool_input") or event.get("input") or {}
if tool != "Bash":
sys.exit(0)
command = str(inp.get("command") or "")
# Match sudo as a command, including sudo -u, sudo -i, and /usr/bin/sudo.
if re.search(r"(^|[;&]|&&|\|\||`|\$\(|\n)\s*(sudo|/usr/bin/sudo|/bin/sudo)\b", command):
print("PreToolUse: blocked sudo. Stay in the repo; do not escalate to root.")
sys.exit(2)
# Also catch a leading sudo after a simple pipe: echo hi | sudo tee file
if re.search(r"\|\s*(sudo|/usr/bin/sudo|/bin/sudo)\b", command):
print("PreToolUse: blocked sudo in a pipeline. Stay in the repo; do not escalate to root.")
sys.exit(2)
Wire it in .claude/settings.json under PreToolUse with command set to python3 .claude/hooks/block_sudo.py. If your settings support a matcher, limit it to Bash.
Why this beats a pasted prompt
"Don't use sudo" in CLAUDE.md only works when the model remembers it mid-turn. After a permission error, the next move is often sudo "just this once." The PreToolUse hook runs before the shell, so that escape hatch is closed. If a package or system file actually needs root, run it yourself in a terminal — do not let the agent escalate.
Tips
- Keep the hook local, fast, and free of network calls.
- Pair it with the
curl | bash, force-push, and--no-verifyPreToolUse guards so install, destructive git, and root escalation are all blocked. - If a test fixture command contains the word sudo in a string, tighten the regex rather than deleting the hook. Quoted commit messages and echo text that do not run sudo will not trip the command-boundary match.
Want the rest of the setup?
I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/
Top comments (0)