Checking for a VPN connection from the command line

I got a question from a reader about how to test if a VPN connection is active and terminate an app if it isn’t. There’s probably a way to do this with Keyboard Maestro or BetterTouchTool or something, but to keep things interesting, I wanted to find a way to do it with just shell scripts.


This is a companion discussion topic for the original entry at https://brettterpstra.com/2024/01/29/checking-for-a-vpn-connection-from-the-command-line

Looks like there’s another CLI in macOS that could potentially be used for this, but I’d have to do some experimentation: scutil --nc list

Apologies if it’s not okay to link to my own content here, but I am using scutil in a very similar way to display my Wireguard icon in my menu bar only when my VPN is actually connected. I documented the process here.

I would highly recommend the use of scutil for this kind of stuff on macOS.

2 Likes

Another suggestion might be to watch your public address, which would also account for device-based VPN termination. I just do a quick dig lookup against opendns, which is included with base MacOS installs.

dig +short myip.opendns.com @resolver1.opendns.com
1 Like

If an app-specific solution would be preferable, there may be a cli tool built for whichever VPN is being used. For example, expresso for ExpressVPN.

Hi,

If you are looking for a non command line solution. Trypa has VPN detection that can trigger a shortcut to quit the app if the VPN is disconnected.

The free version Trypa Lite might be fine if you only want one automation. (I am the developer).

1 Like