Skip to content

Instantly share code, notes, and snippets.

@oskar456
Last active February 27, 2023 03:44
Show Gist options
  • Save oskar456/04e4ed0b9fc20f8148fb62f54f91d4af to your computer and use it in GitHub Desktop.
Save oskar456/04e4ed0b9fc20f8148fb62f54f91d4af to your computer and use it in GitHub Desktop.
Wireguard tunnel watchdog for OpenWRT
#!/bin/sh
check_reachability() {
local target="$1"
local retval
ping6 -c1 -W1 "$target" >/dev/null 2>&1
retval="$?"
[ "$retval" -eq 2 ] && {
ping -c1 -W1 "$target" >/dev/null 2>&1
retval="$?"
}
return $retval
}
get_wg_endpoint() {
local iface="$1"
wg show $iface endpoints 2>/dev/null | sed -rn '1 s_^[^ ]*\s+\[?([0-9a-f:.]+)\]?:[0-9]+$_\1_p' || true
}
get_configured_endpoint() {
local iface="$1"
uci get network.@wireguard_${iface}[0].endpoint_host 2>/dev/null || true
}
check_wg_liveness() {
local iface="${1-wgbb}"
local endpoint=$(get_wg_endpoint $iface)
if [ -z "$endpoint" ]
then
# Tunnel not established
endpoint=$(get_configured_endpoint $iface)
check_reachability $endpoint && {
echo "Endpoint $endpoint reachable, enabling ${iface}…"
ifup $iface
}
else
# Tunnel established
check_reachability $endpoint || {
echo "Endpoint $endpoint unreachable, disabling ${iface}…"
ifdown $iface
}
fi
}
check_wg_liveness wgbb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment