Skip to content

Instantly share code, notes, and snippets.

@mikeboiko
Created February 25, 2025 21:43
Show Gist options
  • Save mikeboiko/79b7f8ae9db8c687b81362435acf74b4 to your computer and use it in GitHub Desktop.
Save mikeboiko/79b7f8ae9db8c687b81362435acf74b4 to your computer and use it in GitHub Desktop.
Tailscale Auto-Connect: Network-Aware VPN Management Script

Tailscale Auto-Connect: Network-Aware VPN Management Script

A NetworkManager dispatcher script that automatically manages your Tailscale VPN connection based on your network environment. It connects to Tailscale when you're on untrusted networks and disconnects when you're on your home network.

#!/bin/bash

INTERFACE=$1
STATUS=$2

HOME_SSID="your_home_wifi_name"
HOST_INTERFACE="your_interface_name"

# Log file for debugging
LOG_FILE="/var/log/tailscale-autoconnect.log"

log() {
    echo "$(date): $1" >>"$LOG_FILE"
}

[ "$INTERFACE" != "$HOST_INTERFACE" ] || exit 0

if [ -n "$(nmcli -t -f active,ssid dev wifi | grep "^yes:${HOME_SSID}")" ]; then
    log "Connected to home wifi: $HOME_SSID. Disabling Tailscale."
    /usr/bin/tailscale down
else
    log "Disconnected from home wifi: $HOME_SSID. Enabling Tailscale."
    /usr/bin/tailscale up --accept-routes --stateful-filtering
fi

Installation

  1. Save the script as /etc/NetworkManager/dispatcher.d/99-tailscale
  2. Make it executable:
sudo chmod +x /etc/NetworkManager/dispatcher.d/99-tailscale

Configuration

  • Edit the HOME_SSID variable in the script to match your home WiFi network name.
  • Edit the HOST_INTERFACE variable in the script to match your interface name. Ex: wlan0.

How it works

  • When connecting to any network that isn't your home network, the script automatically enables Tailscale
  • When connecting to your home network, it disconnects Tailscale to use direct connections
  • Works with NetworkManager's dispatcher system to react to network changes

Requirements

  • NetworkManager
  • Tailscale
  • Linux system
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment