#!/bin/zsh # screensharing-guard.sh —— nc 探测 + 自愈,包括 bootstrap fallback LABEL="com.apple.screensharing" PLIST="/System/Library/LaunchDaemons/com.apple.screensharing.plist" HOST="${HOST:-127.0.0.1}" PORT="${PORT:-5900}" 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_screensharing() { echo "[screensharing-guard] $(date '+%F %T') attempting to restore Screen Sharing..." if ! is_loaded; then echo "[screensharing-guard] service 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_screensharing fi } main