Skip to content

Instantly share code, notes, and snippets.

@RupGautam
Created January 7, 2016 00:09
Show Gist options
  • Select an option

  • Save RupGautam/d3ca0a0dd3ba7ac6b295 to your computer and use it in GitHub Desktop.

Select an option

Save RupGautam/d3ca0a0dd3ba7ac6b295 to your computer and use it in GitHub Desktop.
Start/Stop vpn from command line OSX
#!/bin/bash
# VPN-commandline script @http://superuser.com/questions/358513/start-configured-vpn-from-command-line-osx
set -e
#set -x
act="$1"
vpn="$2"
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 ]
}
if [ "$act" = "start" ]; then
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
elif [ "$act" = "stop" ]; then
if isnt_connected "$vpn"; then
echo "disconnected already"
else
scutil --nc stop "$vpn"
echo "Disconnected $vpn!"
fi
exit 0
else
echo "NOT connected!!! / Invalid action!!!"
fi
@RupGautam

Copy link
Copy Markdown
Author

Steps

Make sure it's executable

chmod +x path/vpn.sh
path/vpn.sh start fooVPN
path/vpn.sh stop fooVPN

optional

Move path/vpn.sh to /usr/local/bin as /usr/local/bin/vpn to make it act like command function

Reload Terminal and you have now vpn as command

Run

vpn start fooVPN
vpn stop fooVPN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment