guarinogabriel / Mac-CLI

 macOS command line tool for developers – The ultimate tool to manage your Mac. It provides a huge set of command line commands that automatize the usage of your Mac.
MIT License
8.86k stars 333 forks source link

VPN command #143

Closed jcalonso closed 6 years ago

jcalonso commented 6 years ago

Hi!

I was looking without luck for a VPN command to connect to any of my current VPN connections. Any ideas how to achieve this?

Thanks!

ThatLurker commented 6 years ago

Why not just use Tunnelblick ?

jcalonso commented 6 years ago

Uhm, as far as I know, Tunnelblick is just for OpenVPN. I use Cisco IPsec which I configure with the normal MacOS VPN configurator. And my use case was because normally I do something like:

jcalonso@macbook:~⟫ ssh some-work-server
ssh: Could not resolve hostname some-work-server...
#Crap! I forgot to connect to the work VPN, so it would be nice to do:
jcalonso@macbook:~⟫ mac vpn:connect work
jcalonso@macbook:~⟫ ssh some-work-server
...
ThatLurker commented 6 years ago

Totally forgot about IPsec. Something like this might work for you, and if it does could you tell me, so i (or someone else) could add it as a mac vpn:connect command

#!/bin/bash

# Call with <script> "<VPN Connection Name>"

set -e
#set -x

vpn="$1"

function isnt_connected () {
    scutil --nc status "$vpn" | sed -n 1p | grep -qv Connected
}

function poll_until_connected () {
    let loops=0 || true
    let max_loops=200 # 200 * 0.1 is 20 seconds. Bash doesn't support floats

    while isnt_connected "$vpn"; do
        sleep 0.1 # can't use a variable here, bash doesn't have floats
        let loops=$loops+1
        [ $loops -gt $max_loops ] && break
    done

    [ $loops -le $max_loops ]
}

scutil --nc start "$vpn"

if poll_until_connected "$vpn"; then
    echo "Connected to $vpn!"
    exit 0
else
    echo "I'm too impatient!"
    scutil --nc stop "$vpn"
    exit 1
fi
jcalonso commented 6 years ago

thanks @pahakalle works perfect!