#!/bin/zsh # sshd-guard.sh —— nc 探测 + 自愈,包括 bootstrap fallback LABEL="com.openssh.sshd" PLIST="/System/Library/LaunchDaemons/ssh.plist" HOST="${HOST:-127.0.0.1}" PORT="${PORT:-22}" TIMEOUT="${TIMEOUT:-1}" while getopts "h:p:t:i:" opt; do case "$opt" in h) HOST="$OPTARG" ;; p) PORT="$OPTARG" ;; t) TIMEOUT="$OPTARG" ;; esac done is_disabled() { launchctl print-disabled system | grep -q "\"$LABEL\" => true"; } is_running() { nc -nzv -G "$TIMEOUT" "$HOST" "$PORT" >/dev/null 2>&1; } is_loaded() { launchctl print system/"$LABEL" >/dev/null 2>&1; } heal_sshd() { echo "[sshd-guard] $(date '+%F %T') attempting to restore sshd..." if ! is_loaded; then echo "[sshd-guard] sshd not loaded, bootstrapping $PLIST" launchctl bootstrap system "$PLIST" 2>/dev/null fi launchctl enable "system/$LABEL" 2>/dev/null launchctl kickstart -k "system/$LABEL" 2>/dev/null } main() { if is_disabled || ! is_running; then heal_sshd fi } main