Skip to content

Instantly share code, notes, and snippets.

@lsr00ter
Last active February 11, 2025 03:36
Show Gist options
  • Save lsr00ter/8c04c1223d9830e2c53fe3869cf26ebf to your computer and use it in GitHub Desktop.
Save lsr00ter/8c04c1223d9830e2c53fe3869cf26ebf to your computer and use it in GitHub Desktop.
WireGuar Watchdog for DDNS endpoint update
#!/bin/bash
set -e
## Put this script in /usr/local/bin/wireguard-watchdog.sh
## Create a service file
# sudo nano /etc/systemd/system/wireguard-watchdog.service
# [Unit]
# Description=WireGuard Watchdog for DDNS endpoint update
# After=network.target
# [Service]
# ExecStart=/usr/local/bin/wireguard-watchdog.sh
# Restart=always
# User=root
# [Install]
# WantedBy=multi-user.target
## Reload systemd and enable the service
# sudo systemctl daemon-reload
# sudo systemctl enable wireguard-watchdog.service
# sudo systemctl start wireguard-watchdog.service
log() {
local message="$(date '+%Y-%m-%d %H:%M:%S') - $*"
echo "$message" >> "$LOG_FILE" # Write to custom log file
logger -t "wireguard-watchdog" "$@" # Keep syslog entry if needed
}
watchdog(){
# Configuration
HOSTNAME="WIREGUARD_PUBLIC_ENDPOINT" # Wireguard hostname
IP_FILE="/var/tmp/last_known_ip" # Storage for previous IP
SLEEP=300 # 5 minutes between checks
LOG_FILE="/var/log/wireguard-watchdog.log"
LOG_LEVEL=3
[ -f "$LOG_FILE" ] || touch "$LOG_FILE" && chmod 644 "$LOG_FILE"
echo "WireGuard watchdog: started, checking $HOSTNAME every $SLEEP seconds"
log "Service started, checking $HOSTNAME every $SLEEP seconds"
while sleep "$SLEEP"; do
for i in {1..3}; do
current_ip=$(dig +short "$HOSTNAME" @119.29.29.29 | head -n1) || true
if [ -n "$current_ip" ]; then
break
fi
sleep 2
done
if [ -z "$current_ip" ]; then
log "Failed to resolve IP address after 3 attempts" >&2
fi
previous_ip=$(cat "$IP_FILE" 2>/dev/null)
if [ "$current_ip" != "$previous_ip" ]; then
echo "IP changed from ${previous_ip:-none} to $current_ip"
log "IP changed from ${previous_ip:-none} to $current_ip"
echo "$current_ip" > "$IP_FILE"
systemctl restart wg-quick@wg0 # Make sure wg0 is the correct wireguard interface
echo "Successfully restarted service with new IP $current_ip"
log "Successfully restarted service with new IP $current_ip"
else
echo "No IP change detected for $HOSTNAME"
log "No IP change detected for $HOSTNAME"
fi
done
}
# Start the watchdog
watchdog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment