Skip to content

Instantly share code, notes, and snippets.

@arikw
Created July 7, 2024 12:13
Show Gist options
  • Save arikw/93ff1ecfa406d73c04e4a02e75dc5542 to your computer and use it in GitHub Desktop.
Save arikw/93ff1ecfa406d73c04e4a02e75dc5542 to your computer and use it in GitHub Desktop.

How to automatically enable\disable wireguard connection upon WIFI connection status change

Prerequisits

  • Gnome 40 and above (Tested on Gnome 46)
  • An already configured wireguard VPN connection (via the NetworkManager)

Steps

  • Using root, create a script file in /etc/NetworkManager/dispatcher.d/wireguard.sh and make it executable ug+x
  • Add the following content:
    #!/usr/bin/env bash
    
    interface=$1
    event=$2
    active_wg=$(nmcli connection show --active | grep wireguard | cut -d " " -f1)
    wireguard_connection_name="PUT_HERE_YOUR_WIREGUARD_CONNECTION_ID"
    
    if [[ "$interface" = "wlo1" ]] && [[ "$event" = "down" ]] && [[ -n "$active_wg" ]]; then
      echo "WIREGUARD: wifi is down. turning off wireguard" | systemd-cat -p info -t wireguard
      nmcli connection down "$wireguard_connection_name";
    fi
    
    if [[ "$interface" = "wlo1" ]] && [[ "$event" = "up" ]] && [[ -z "$active_wg" ]]; then
      echo "WIREGUARD: wifi is up. turning on wireguard" | systemd-cat -p info -t wireguard
      nmcli connection up "$wireguard_connection_name";
    fi
  • Find your wireguard connection id using nmcli connection show | grep wireguard and notice the 1st column in the output
  • Replace the "PUT_HERE_YOUR_WIREGUARD_CONNECTION_ID" in the above wireguard.sh file
  • The wireguard connection should now follow the status of your wifi
  • Debug using journalctl, e.g., journalctl --utc --since "15 minutes ago" -t wireguard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment