Skip to content

Instantly share code, notes, and snippets.

@rossigee
Created November 18, 2023 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossigee/4e3d2adb89550d83e552010d0e0f789a to your computer and use it in GitHub Desktop.
Save rossigee/4e3d2adb89550d83e552010d0e0f789a to your computer and use it in GitHub Desktop.
Bash script to manage Wireguard dynamic IP endpoint
#!/usr/bin/env bash
# Settings
WG_IFACE=wg0
WG_PEER=<peer_id>
WG_PORT=12345
HOSTNAME=yourhostname.dynamicip.example.com
# File to store the last IP
last_ip_file="/tmp/last_ip.txt"
# Initialize last IP
if [ ! -f "$last_ip_file" ]; then
echo "0.0.0.0" > "$last_ip_file"
fi
# Fetch current IP
current_ip=$(dig +short $HOSTNAME)
# Read last IP
last_ip=$(cat "$last_ip_file")
# Compare with the last IP
if [ "$current_ip" != "$last_ip" ]; then
echo "IP has changed to '$current_ip'. Restarting wg0."
wg set $WG_IFACE peer $WG_PEER endpoint $current_ip:$WG_PORT
echo "$current_ip" > "$last_ip_file"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment