This is the second part of the Availability Anywhere series. For your convenience you can find other parts in the table of contents in Part 1 – Connecting to SSH tunnel automatically in Windows
Last week we saw how to configure automatic SSH tunnel connection. Today we will go with VPN.
I am using built-in VPN provider (SSTP and L2TP) supported by rasdial.
First, configure your VPN (using either PS or GUI). It doesn’t matter which options you choose, just make sure it works and can connect correctly.
Next, it’s time to set up a script for automatically connecting to VPN:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
ping -n 1 YOUR_VPN_SERVER_IP | find "time=" > NUL if not errorlevel 1 ( netsh interface IPv4 set dnsserver "Wi-Fi" static 0.0.0.0 both netsh interface IPv4 set dnsserver "Local Area Connection" static 0.0.0.0 both exit ) rasdial VPN_NAME /disconnect netsh interface IPv4 set dnsserver "Wi-Fi" source="dhcp" netsh interface IPv4 set dnsserver "Local Area Connection" source="dhcp" rasdial VPN_NAME USERNAME PASSWORD ping -n 1 YOUR_VPN_SERVER_IP | find "time=" > NUL if not errorlevel 1 ( netsh interface IPv4 set dnsserver "Wi-Fi" static 0.0.0.0 both netsh interface IPv4 set dnsserver "Local Area Connection" static 0.0.0.0 both ) |
This script does multiple things. First, in lines 1 to 6 I check if I am already connected. I am running this script frequently (each minute) and I want to disable DNS leaking so I set DNS Server to invalid address for regular network interfaces when I’m connected. If everything is okay, I exit in line 5.
If I cannot reach the server then I disconnect (line 8), I restore DHCP for DNS resolution and then in line 12 I try connecting. Finally, I check if I’m connected and then reset DNS again.
This configuration works for “regular” networks (like at home or in my office) and also for those hotel WiFis requiring authentication via browser. If it detects it cannot connect to VPN server then it resets settings to DHCP and then I can authenticate in the browser.
Now, you need to have task for task scheduler. This is almost the same as last week only this time I’m running it as a user in which I log into the machine. Just keep in mind that when you change your password then you need to go to task scheduler, open settings of the task, close them and enter new password, then restart your computer.