Block Service Restarts Outside a Change Window

Pairs with a standing deploy-approval policy: even once a restart command is approved in spirit, this enforces *when* it's allowed to actually run, so an agent working an off-hours session can't accidentally cause a mid-day outage.

Production Guardrails Event: PreToolUse Claude Code Open source · Free

1. Save this as the hook script

#!/usr/bin/env python3
"""PreToolUse hook — blocks systemctl restart/stop outside a configured
maintenance window. Wire this to the Bash matcher."""
import json, re, sys, datetime

data = json.load(sys.stdin)
command = (data.get("tool_input") or {}).get("command", "")

if not re.search(r"systemctl\s+(restart|stop)\s+\S+", command):
    sys.exit(0)

WINDOW_START, WINDOW_END = 22, 2  # 10pm-2am local, wraps midnight
hour = datetime.datetime.now().hour
in_window = hour >= WINDOW_START or hour < WINDOW_END

if not in_window:
    print(f"BLOCKED: service restarts are only allowed {WINDOW_START}:00-{WINDOW_END}:00. "
          f"Current hour: {hour}:00.", file=sys.stderr)
    sys.exit(2)

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/block-restarts-outside-change-window.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/block-restarts-outside-change-window.py"}
        ]
      }
    ]
  }
}

Before you use this

A hook runs with your local shell's permissions — review the script above before adding it, the same way you'd review any script you didn't write yourself. See our guide on hook security risks for the specific CVEs this category of feature has already produced.

Related hooks

← All hooks
FEEDBACK