OdinBrood
OdinBrood

Reputation: 23

Batch script to bypass VPN for certain domains

I've been using a VPN service for some time but some websites (twitch.tv) do not allow me to connect to them via a VPN. So I looked up how to bypass the VPN for these domains on Windows and found static routing.

How I wanted to do it was with a batch file to run on startup that automatically routes all the ip adresses of a set of given domains.

This is what I came up with through trial and error.

@echo off

FOR /F "tokens=3" %%F in (
    'route print ^|findstr "\<0.0.0.0\>"'
) Do if not defined DefaultGateway set "DefaultGateway=%%F"

FOR /F "tokens=2" %%F in ('nslookup twitch.tv') DO (
    SET var1=%%F
)
route -p add %var1% mask 255.255.255.255 %DefaultGateway%

FOR /F "skip=5 tokens=1" %%F IN ('nslookup twitch.tv') DO (
   route -p add %%F mask 255.255.255.255 %DefaultGateway%
)

I think you can tell that this is some hideous frankenstein code that I created from snippets found on SO. It works for now, but how would I make it more elegant? Could the second and third FOR loop be combined into one? How do I make it so that if I were to add a new domain I could just add it to a list instead of adding another 2 FOR loops?

Upvotes: 2

Views: 1158

Answers (1)

woxxom
woxxom

Reputation: 73616

I had been using this batch file:

set domains=twitch.tv google.com some-domain.com

for /f "tokens=3" %%a in ('route print ^| findstr "\<0.0.0.0\>"') do (
    for %%d in (%domains%) do (
        for /f "tokens=1,2 skip=4" %%b in ('nslookup %%d 2^>nul') do (
            if "%%c"=="" (route add %%b %%a) else (route add %%c %%a)
        )
    )
    goto done
)
:done

It grabs the first 0.0.0.0 route's gateway and uses it to add the routes for the specified domains, their IP addresses obtained via nslookup.

And it was scheduled to run whenever the connection was established via Task Scheduler -> Microsoft -> Windows -> Ras with the trigger On an event / Application / RasClient / 20225.

Upvotes: 1

Related Questions