Skip to content

Instantly share code, notes, and snippets.

@tperalta82
Last active August 18, 2024 02:37
Show Gist options
  • Save tperalta82/8d6a9785322d4001ca4ec651b51739f7 to your computer and use it in GitHub Desktop.
Save tperalta82/8d6a9785322d4001ca4ec651b51739f7 to your computer and use it in GitHub Desktop.
Wireguard DDNS Updater
import re
import subprocess
import socket
import traceback
DEBUG = False
WG = "wg0"
DDNS = "ddnshost.tld"
try:
subprocess.run(["wg-quick", "save", f'{WG}'])
config = open(f'/etc/wireguard/{WG}.conf', "r").read()
old_ip = None
for line in config.split("\n"):
if not line.startswith("Endpoint"):
continue
ip_addr_regex = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
old_ip = re.findall(ip_addr_regex, line)[0]
n_ip = socket.gethostbyname(DDNS)
if (old_ip is not None and n_ip != old_ip) or DEBUG:
subprocess.run(["wg-quick", "down", f'{WG}'])
nconfig = open(f'/etc/wireguard/{WG}.conf', "w").write(config.replace(old_ip, n_ip))
subprocess.run(["wg-quick", "up", f'{WG}'])
except Exception:
traceback.print_exc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment