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.

#!/bin/bash

SSID=$(networksetup -getairportnetwork en0 | cut -c 24-)
CONNECTION_NAME="PIA US East"
WHITELIST_SSIDS=("Millennium Falcon" "USS Enterprise")
UNTRUSTED=true

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

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

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/com.apple.airport.preferences.plist is changed.

Create this file in ~/Library/LaunchAgents/com.jpadilla.network-change.plist. Be sure to update PATH_TO_NETWORK_CHANGE_SCRIPT with the actual path of the script from the previous part.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" \ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>network-change</string>

  <key>LowPriorityIO</key>
  <true/>

  <key>ProgramArguments</key>
  <array>
    <string>PATH_TO_NETWORK_CHANGE_SCRIPT</string>
  </array>

  <key>WatchPaths</key>
  <array>
    <string>/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist</string>
  </array>

  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

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

launchctl load ~/Library/LaunchAgents/com.jpadilla.network-change.plist

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

Leave a Reply

Your email address will not be published. Required fields are marked *