Keep that VPN Connected (MacOS)

osx vpn 
↞ See all posts

I recently found myself regularly traveling, and I wanted to ensure that no matter when I opened my laptop, that my wifi connection would be secure. However, there’s no way using built-in OSX VPN client to connect on boot or wake-from-sleep, nor is there any way retry after the failure of your VPN connection. Good thing that Apple made AppleScript!

I have a personal VPN server running on a 5$/mo Digital Ocean server which is configured with this amazing script: I’ve got my VPN configured in the MacOS Network settings as vpn-evan and I’ve got "all network traffic" going though it. That should keep me safe…

Create the Reconnection Script

Open Script Editor and paste in the following:

1on idle 2 tell application "System Events" 3 tell current location of network preferences 4 set VPNService to the service "vpn-evan" -- replace this with the name of your VPN connection 5 if VPNService is not null then 6 if current configuration of VPNService is not connected then 7 beep 8 beep 9 beep 10 connect VPNService 11 end if 12 end if 13 end tell 14 end tell 15 -- in "idle" blocks, the number returned is how long to sleep until running again 16 return 60 17end idle

Let’s break dow this script:

  1. When the application is idle
  2. Find your VPN connection
  3. If it’s disconnected, beep at us (so we know what’s happening), and then try to connect
  4. Sleep for 60 seconds and check again

Be sure to replace "vpn-evan" above with the name of your VPN connection

So if this program is always running in the background, every minute, you will try to connect to your VPN!

Configure the Application to Run at Boot

Now, we want to turn this little script into a program.

1. In `Script Editor`, go to "export" and save your script as an "application". Click "Stay open after Run Handler"

2. Open up `System Preferences` and then navigate to "Users" and "Startup Items". Drag and Drop your new application there!

That’s it!

Thanks to

Hi, I'm Evan

I write about Technology, Software, and Startups. I use my Product Management, Software Engineering, and Leadership skills to build teams that create world-class digital products.

Get in touch