MacOS – Start Configured VPN from Command Line

command linemacososx lionvpn

I have two VPN configurations on my mac and I would like to be able to start them from the console when I ssh into my machine.

I have found the command networksetup which allows me to configure connections, but as far as I can tell not actually start one.

Using Lion.

Best Answer

For newer macOS versions, a very simple command can be used, as shown in the below answers, e.g. this one (give it a +1!).

All you need is:

 networksetup -connectpppoeservice "UniVPN"

The only problem is that you cannot disconnect using this command.


You can also use AppleScript to connect to the VPN services of your choice. We'll use shell functions, which are available from the command line, once they are loaded.

Add the functions below to your ~/.bash_profile or ~/.profile (whatever you use).

You just need to change the name of the VPN connection itself, as it appears under the Network preferences. I used my university VPN here.

enter image description here

You can change the names of the functions as well, if you want to do it for different ones. It might be possible to shorten this using arguments, but it works just fine this way. I tested it on Snow Leopard (but Leopard and Lion should work too).

Once you've added the functions, reload the terminal and call them with vpn-connect and vpn-disconnect, respectively.


function vpn-connect {
/usr/bin/env osascript <<-EOF
tell application "System Events"
        tell current location of network preferences
                set VPN to service "UniVPN" -- your VPN name here
                if exists VPN then connect VPN
                repeat while (current configuration of VPN is not connected)
                    delay 1
                end repeat
        end tell
end tell
EOF
}

function vpn-disconnect {
/usr/bin/env osascript <<-EOF
tell application "System Events"
        tell current location of network preferences
                set VPN to service "UniVPN" -- your VPN name here
                if exists VPN then disconnect VPN
        end tell
end tell
return
EOF
}
Related Question