Skip to content

Instantly share code, notes, and snippets.

@oskar456
Last active February 27, 2023 03:44

Revisions

  1. oskar456 revised this gist Aug 22, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion wgwatchdog.sh
    Original file line number Diff line number Diff line change
    @@ -14,7 +14,7 @@ check_reachability() {

    get_wg_endpoint() {
    local iface="$1"
    wg show $iface endpoints 2>/dev/null | sed -rn '1 s_^[^ ]*\s+\[?(.*)\]?:[0-9]+$_\1_p' || true
    wg show $iface endpoints 2>/dev/null | sed -rn '1 s_^[^ ]*\s+\[?([0-9a-f:.]+)\]?:[0-9]+$_\1_p' || true
    }

    get_configured_endpoint() {
  2. oskar456 created this gist Aug 22, 2020.
    47 changes: 47 additions & 0 deletions wgwatchdog.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    #!/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-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