Blog | G5 Cyber Security

VPN Auto-Connect by Website

TL;DR

This guide shows you how to automatically switch your VPN connection based on which website you’re visiting. We’ll use a combination of routing rules and a script that monitors network traffic.

Prerequisites

Step 1: Identify Your VPN Interface and Default Gateway

First, you need to find out the network interface name used by your VPN and its default gateway.

Example (Linux):

ip addr show tun0

Example (PowerShell):

Get-NetAdapter | Where {$_.Name -like "*VPN*"}

Step 2: Create a Routing Script

This script will add and remove routes to force traffic through the VPN for specific websites.

  1. Create a new file, e.g., vpn_route.sh (Linux) or vpn_route.ps1 (PowerShell).
  2. Add the following script content (adapt interface and gateway to your system):

Example Script (Bash – Linux):

#!/bin/bash

VPN_INTERFACE="tun0"
VPN_GATEWAY="192.168.10.1"
WEBSITES=("example.com" "anotherwebsite.net")

for website in ${WEBSITES[@]};
do
  if ping -c 1 $website > /dev/null;
then
    ip route add $website via $VPN_GATEWAY dev $VPN_INTERFACE
echo "Route added for $website"
  else
    ip route del $website via $VPN_GATEWAY dev $VPN_INTERFACE > /dev/null 2&1
echo "Route removed for $website"
  fi
done

Example Script (PowerShell – Windows):

$VPNInterface = "Ethernet 2" # Replace with your VPN interface name
$VPNGateway = "192.168.10.1"
$Websites = @("example.com", "anotherwebsite.net")

foreach ($Website in $Websites) {
  if (Test-Connection -ComputerName $Website -Count 1 -Quiet) {
    New-NetRoute -DestinationPrefix $Website -InterfaceIndex $(Get-NetAdapter -Name $VPNInterface).InterfaceIndex -NextHop $VPNGateway
    Write-Host "Route added for $Website"
  } else {
    Remove-NetRoute -DestinationPrefix $Website -Confirm:$false
    Write-Host "Route removed for $Website"
  }
}

Important: Replace tun0, 192.168.10.1 and the website names with your actual values.

Step 3: Make the Script Executable (Linux)

If you’re using Linux, make sure the script is executable:

chmod +x vpn_route.sh

Step 4: Schedule the Script to Run Regularly

  1. Linux (using cron): Open your crontab editor with crontab -e and add a line like this:
    */5 * * * * /path/to/vpn_route.sh (This runs the script every 5 minutes).
  2. Windows (using Task Scheduler): Create a new task in Task Scheduler.
    • Set the trigger to run regularly (e.g., every 5 minutes).
    • Set the action to run PowerShell and execute your script: powershell -ExecutionPolicy Bypass -File C:pathtovpn_route.ps1. You may need to adjust the ExecutionPolicy depending on your system settings.

Step 5: Test Your Setup

Connect to your VPN, then visit one of the websites you added to the script. Check your IP address (e.g., using WhatIsMyIP) to confirm that it’s coming from your VPN server. Disconnect from the VPN and revisit the website; your IP should revert to your normal connection.

Troubleshooting

Exit mobile version