Skip to content

Instantly share code, notes, and snippets.

@magicstone1412
Created September 15, 2024 23:03
Show Gist options
  • Save magicstone1412/c338c2bba76aeab53a44d6e49aad9e42 to your computer and use it in GitHub Desktop.
Save magicstone1412/c338c2bba76aeab53a44d6e49aad9e42 to your computer and use it in GitHub Desktop.
Auto reconnect Wireguard on Debian
#!/bin/bash
# Function to check internet connection
check_internet() {
if ping -q -c 1 -W 1 8.8.8.8 >/dev/null 2>&1; then
return 0 # Internet is available
else
return 1 # No internet connection
fi
}
# Function to check if WireGuard is running
check_wireguard() {
if systemctl is-active --quiet wg-quick@wg0; then
return 0 # WireGuard is running
else
return 1 # WireGuard is not running
fi
}
# Check internet connection
if check_internet; then
echo "Internet connection is available."
# Check if WireGuard is running
if check_wireguard; then
echo "WireGuard is already running. Exiting."
exit 0
else
echo "WireGuard is not running. Starting WireGuard."
wg-quick up wg0
exit 0
fi
else
echo "No internet connection. Turning off WireGuard."
# Turn off WireGuard
wg-quick down wg0
# Wait for 3 seconds
sleep 3
# Check internet connection again
if check_internet; then
echo "Internet is back. Starting WireGuard."
wg-quick up wg0
else
echo "No internet connection after retry. Exiting."
exit 0
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment