Connecting to a VPN automatically when not at home

When I’m on my home Wi-Fi, I rarely connect to a VPN. When I’m out, I always make the habit of doing so, except when I forget. I was hoping VPN clients would have a feature to automatically connect based on a list of networks, but after some quick research, I guess not. Maybe I’m wrong, but ended up with this nifty solution. I’m currently using Viscosity as my VPN client, but should work similarly for other clients that allow some scripting.

First part, place this bash script somewhere and make it executable.  You’ll probably want to update CONNECTION_NAME, the name of the VPN connection you want to use and WHITELIST_SSIDS, the SSID of the Wi-Fi networks you trust. Go ahead and try it out by executing it when connected to different Wi-Fi networks.

[code language=”plain” light=”true”]


SSID=$(networksetup -getairportnetwork en0 | cut -c 24-)
WHITELIST_SSIDS=("Millennium Falcon" "USS Enterprise")

for ssid in "${WHITELIST_SSIDS[@]}"; do
if [[ "$SSID" == "$ssid" ]]; then

if [[ $UNTRUSTED == true ]]; then
osascript -e "tell application \"Viscosity\" to connect \"$CONNECTION_NAME\""


Next, we’ll want to make this happen automatically with a launch agent. This will execute the bash script above every time the /Library/Preferences/SystemConfiguration/ is changed.

Create this file in ~/Library/LaunchAgents/ Be sure to update PATH_TO_NETWORK_CHANGE_SCRIPT with the actual path of the script from the previous part.

[code language=”plain” light=”true”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" \ "">
<plist version="1.0">





You can run the following to load service without having to login again:

launchctl load ~/Library/LaunchAgents/

That’s it! Try connecting to different Wi-Fi networks and watch your VPN automatically connect.