VPN Connection Scripts allow you to automate virtually any action when your VPN connects, disconnects, or before connecting. This powerful feature enables custom workflows like launching secure applications, changing DNS settings, modifying firewall rules, or sending notifications - all triggered by VPN state changes.
🔧 Script Automation Possibilities
- Security: Enable firewall rules, change DNS, flush caches
- Applications: Launch/close apps, mount drives, sync files
- Networking: Update routes, change MTU, configure proxies
- Notifications: Send alerts, log connections, update status
- System: Change power settings, switch profiles, backup configs
Understanding Script Types
Script Type | When It Runs | Common Uses | Access to VPN Info |
---|---|---|---|
Pre-Connect | Before VPN connects | Prepare system, check requirements | Limited |
Connect | After VPN establishes | Launch apps, update settings | Full |
Disconnect | After VPN disconnects | Cleanup, restore settings | Previous connection |
Configuration Steps
Step 1: Access TorGuard Settings
- Open TorGuard desktop client
- Click the settings button

Step 2: Configure Scripts
- Navigate to the "Scripts" tab
- Check "Execute scripts" checkbox
- Select connection phase:
- Pre-connect
- Connect
- Disconnect
- Browse to locate your script file
- Click Save to apply

Windows Batch Scripts
Example 1: Internet Kill Switch
@echo off
REM Kill Switch - Disable adapters except VPN
:: On Connect - Disable other adapters
if "%1"=="connected" (
netsh interface set interface "Wi-Fi" disable
netsh interface set interface "Ethernet" disable
echo Kill switch activated
)
:: On Disconnect - Re-enable adapters
if "%1"=="disconnected" (
netsh interface set interface "Wi-Fi" enable
netsh interface set interface "Ethernet" enable
echo Kill switch deactivated
)
Example 2: Launch Secure Applications
@echo off
REM Launch apps after VPN connects
if "%1"=="connected" (
:: Launch torrent client
start "" "C:\Program Files\qBittorrent\qbittorrent.exe"
:: Launch secure browser
start "" "C:\Program Files\Mozilla Firefox\firefox.exe" -private
:: Open secure folder
explorer "D:\SecureDocuments"
echo Secure applications launched
)
Example 3: Dynamic DNS Configuration
@echo off
REM Set custom DNS based on VPN status
if "%1"=="connected" (
:: Use secure DNS
netsh interface ip set dns "Wi-Fi" static 1.1.1.1
netsh interface ip add dns "Wi-Fi" 1.0.0.1 index=2
ipconfig /flushdns
echo DNS changed to Cloudflare
)
if "%1"=="disconnected" (
:: Restore automatic DNS
netsh interface ip set dns "Wi-Fi" dhcp
ipconfig /flushdns
echo DNS restored to automatic
)
Example 4: Website Launch & Verification
@echo off
REM Open websites after connection
if "%1"=="connected" (
:: Wait for connection to stabilize
timeout /t 3 /nobreak > nul
:: Check IP and open sites
start https://torguard.net/checkmyipaddress.php
start https://dnsleaktest.com
:: Open work sites
start https://mycompany.internal.com
)
Linux/Mac Shell Scripts
Example 1: Firewall Rules (iptables)
#!/bin/bash
# Advanced firewall script for VPN
case "$1" in
connected)
# Get VPN interface
VPN_IF=$(ip route | grep default | grep -v "$(ip route | grep default | head -1 | awk '{print $5}')" | awk '{print $5}')
# Block all non-VPN traffic
sudo iptables -I OUTPUT ! -o $VPN_IF -j DROP
sudo iptables -I INPUT ! -i $VPN_IF -j DROP
# Allow LAN
sudo iptables -I OUTPUT -d 192.168.0.0/16 -j ACCEPT
sudo iptables -I INPUT -s 192.168.0.0/16 -j ACCEPT
echo "Firewall rules applied for $VPN_IF"
;;
disconnected)
# Remove VPN rules
sudo iptables -D OUTPUT ! -o tun+ -j DROP 2>/dev/null
sudo iptables -D INPUT ! -i tun+ -j DROP 2>/dev/null
echo "Firewall rules removed"
;;
esac
Example 2: Network Manager Integration
#!/bin/bash
# Manage network connections with VPN
case "$1" in
connected)
# Disable Wi-Fi to force VPN-only
nmcli radio wifi off
# Mount network drives
mount -t cifs //nas/secure /mnt/secure -o credentials=/home/user/.smbcreds
# Start services
systemctl start transmission-daemon
;;
disconnected)
# Re-enable Wi-Fi
nmcli radio wifi on
# Unmount sensitive drives
umount /mnt/secure
# Stop services
systemctl stop transmission-daemon
;;
esac
Example 3: macOS Specific
#!/bin/bash
# macOS VPN automation script
case "$1" in
connected)
# Change DNS
networksetup -setdnsservers Wi-Fi 1.1.1.1 1.0.0.1
# Launch apps
open -a "Transmission"
open -a "Firefox" --args -private-window
# Send notification
osascript -e 'display notification "VPN Connected" with title "TorGuard"'
;;
disconnected)
# Restore DNS
networksetup -setdnsservers Wi-Fi empty
# Kill sensitive apps
killall Transmission
# Notification
osascript -e 'display notification "VPN Disconnected" with title "TorGuard"'
;;
esac
Advanced Script Examples
Multi-Action Windows Script
@echo off
REM Advanced VPN automation script
set ACTION=%1
set VPN_IP=%2
set VPN_LOCATION=%3
if "%ACTION%"=="connected" (
:: Log connection
echo %date% %time% - Connected to %VPN_IP% (%VPN_LOCATION%) >> C:\vpn_log.txt
:: Update hosts file for internal sites
echo 10.8.0.100 internal.site >> C:\Windows\System32\drivers\etc\hosts
:: Set static routes
route add 10.0.0.0 mask 255.0.0.0 %VPN_IP%
:: Change power plan
powercfg /setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
:: Start scheduled tasks
schtasks /run /tn "SecureBackup"
)
if "%ACTION%"=="disconnected" (
:: Cleanup hosts file
findstr /v "internal.site" C:\Windows\System32\drivers\etc\hosts > temp.txt
move /y temp.txt C:\Windows\System32\drivers\etc\hosts
:: Remove routes
route delete 10.0.0.0
:: Restore power plan
powercfg /setactive 381b4222-f694-41f0-9685-ff5bb260df2e
)
Python Cross-Platform Script
#!/usr/bin/env python3
import sys
import os
import subprocess
import platform
from datetime import datetime
def on_connect():
"""Actions to perform on VPN connect"""
print(f"VPN Connected at {datetime.now()}")
# Cross-platform DNS change
if platform.system() == "Windows":
subprocess.run(["netsh", "interface", "ip", "set", "dns", "Wi-Fi", "static", "1.1.1.1"])
elif platform.system() == "Darwin": # macOS
subprocess.run(["networksetup", "-setdnsservers", "Wi-Fi", "1.1.1.1", "1.0.0.1"])
else: # Linux
# Modify resolv.conf
with open("/etc/resolv.conf", "w") as f:
f.write("nameserver 1.1.1.1\nnameserver 1.0.0.1\n")
# Launch applications
apps = {
"Windows": ["C:\\Program Files\\qBittorrent\\qbittorrent.exe"],
"Darwin": ["open", "-a", "Transmission"],
"Linux": ["transmission-gtk"]
}
if platform.system() in apps:
subprocess.Popen(apps[platform.system()])
def on_disconnect():
"""Actions to perform on VPN disconnect"""
print(f"VPN Disconnected at {datetime.now()}")
# Kill sensitive applications
if platform.system() == "Windows":
subprocess.run(["taskkill", "/F", "/IM", "qbittorrent.exe"])
else:
subprocess.run(["pkill", "-f", "transmission"])
if __name__ == "__main__":
if len(sys.argv) > 1:
if sys.argv[1] == "connected":
on_connect()
elif sys.argv[1] == "disconnected":
on_disconnect()
Available Environment Variables
TorGuard passes these variables to scripts:
Variable | Description | Example |
---|---|---|
%1 / $1 | Connection status | connected/disconnected |
%2 / $2 | VPN server IP | 89.187.178.123 |
%3 / $3 | Server location | USA-NEWYORK |
%4 / $4 | Protocol used | OpenVPN/WireGuard |
Ready-to-Use Script Templates
📥 Download Script Templates
Script Best Practices
- Error Handling: Always include error checking
if errorlevel 1 ( echo Error occurred >> error.log exit /b 1 )
- Logging: Keep logs for debugging
echo %date% %time% - Script executed >> vpn_script.log
- Timeouts: Add delays for stability
timeout /t 5 /nobreak > nul
- Admin Rights: Request elevation when needed
:: Check for admin rights net session >nul 2>&1 if %errorlevel% neq 0 ( echo Requesting administrator privileges... powershell Start-Process cmd -ArgumentList '/c %~f0' -Verb RunAs exit /b )
Troubleshooting Scripts
Script Not Running
- Permissions: Ensure script is executable (chmod +x on Linux/Mac)
- Path: Use absolute paths in scripts
- Admin rights: Some commands require elevation
- Script type: Match script type to OS (.bat for Windows, .sh for Linux/Mac)
Script Errors
- Test manually: Run script from command line first
- Add debugging: Echo commands to see execution
- Check logs: Look for error messages
- Syntax: Validate script syntax for your shell
Security Considerations
⚠️ Script Security
- Store scripts in protected directories
- Don't hardcode passwords - use environment variables
- Validate all inputs to prevent injection
- Review scripts before enabling auto-execution
- Use minimal privileges required
Creative Use Cases
Use Case | Pre-Connect | Connect | Disconnect |
---|---|---|---|
Work VPN | Check time/location | Mount drives, open apps | Unmount, lock screen |
Streaming | Close bandwidth apps | Launch media player | Restore settings |
Gaming | Optimize network | Launch game, Discord | Restore normal settings |
Privacy | Clear caches | Start Tor, secure apps | Secure wipe temp files |
Need Script Help?
Our support team can help you create custom scripts for your specific automation needs or troubleshoot existing scripts.
Get Script Support