Skip to content

Instantly share code, notes, and snippets.

@jizusun
Created August 6, 2026 18:07
Show Gist options
  • Select an option

  • Save jizusun/402ec8d654e42bbcb943ec630b3979fa to your computer and use it in GitHub Desktop.

Select an option

Save jizusun/402ec8d654e42bbcb943ec630b3979fa to your computer and use it in GitHub Desktop.
Keep macOS awake while Cisco VPN is connected
#!/bin/bash
# Keep macOS awake while Cisco VPN is connected.
# Uses caffeinate to prevent sleep when a utun interface (VPN tunnel) is active.
#
# Usage:
# ./keep-awake-on-vpn.sh # run in foreground
# ./keep-awake-on-vpn.sh & # run in background
#
# Stop: kill the script (or Ctrl+C if in foreground)
CHECK_INTERVAL=30 # seconds between checks
CAFFEINATE_PID=""
is_vpn_connected() {
# Cisco AnyConnect/Secure Client creates utun interfaces when connected.
# Also check for the Cisco process as a secondary signal.
if ifconfig | grep -q "^utun"; then
# Verify there's actual traffic capability (interface has an IP)
if ifconfig | grep -A5 "^utun" | grep -q "inet "; then
return 0
fi
fi
return 1
}
start_caffeinate() {
if [ -z "$CAFFEINATE_PID" ]; then
# -d: prevent display sleep
# -i: prevent idle sleep
# -s: prevent system sleep (on AC power)
caffeinate -dis &
CAFFEINATE_PID=$!
echo "$(date): VPN connected — keeping Mac awake (caffeinate PID: $CAFFEINATE_PID)"
fi
}
stop_caffeinate() {
if [ -n "$CAFFEINATE_PID" ]; then
kill "$CAFFEINATE_PID" 2>/dev/null
wait "$CAFFEINATE_PID" 2>/dev/null
CAFFEINATE_PID=""
echo "$(date): VPN disconnected — allowing sleep"
fi
}
cleanup() {
stop_caffeinate
echo "$(date): Script stopped"
exit 0
}
trap cleanup EXIT INT TERM
echo "$(date): Monitoring Cisco VPN connection (checking every ${CHECK_INTERVAL}s)..."
while true; do
if is_vpn_connected; then
start_caffeinate
else
stop_caffeinate
fi
sleep "$CHECK_INTERVAL"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment