Skip to content

Instantly share code, notes, and snippets.

@MorphyDK
Created April 23, 2025 05:08
Show Gist options
  • Select an option

  • Save MorphyDK/5cb27744b5b26ddd5cf8921eedcc3281 to your computer and use it in GitHub Desktop.

Select an option

Save MorphyDK/5cb27744b5b26ddd5cf8921eedcc3281 to your computer and use it in GitHub Desktop.
VPN watchdog - monitor if vpn tunnel is up.
#!/bin/bash
# Config
INTERFACE="wg0"
SERVICE="wg-quick@${INTERFACE}.service"
CHECK_INTERVAL=30
MAX_RETRIES=5
RETRY_DELAY=10
check_vpn() {
ping -c 2 -W 2 YOURVPNIPHERE > /dev/null 2>&1 # Replace with your VPN endpoint or a pingable host only accessible through VPN
return $?
}
restart_vpn() {
echo "[INFO] VPN seems down. Restarting $SERVICE..."
sudo systemctl restart "$SERVICE"
}
reboot_server() {
echo "[ERROR] VPN still not working after $MAX_RETRIES attempts. Rebooting system..."
sudo reboot
}
while true; do
if ! check_vpn; then
echo "[WARNING] VPN connection appears to be down."
attempts=0
while ! check_vpn && [ $attempts -lt $MAX_RETRIES ]; do
restart_vpn
sleep $RETRY_DELAY
((attempts++))
done
if ! check_vpn; then
reboot_server
fi
else
echo "[INFO] VPN is up."
fi
sleep $CHECK_INTERVAL
done
@MorphyDK
Copy link
Author

Create a service or add to crontab.

Systems service could be :

[Unit]
Description=VPN Watchdog for WireGuard
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/local/bin/vpn-watchdog.sh
Restart=always
RestartSec=10
User=root

[Install]
WantedBy=multi-user.target

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment