Skip to content

Instantly share code, notes, and snippets.

@pasdam
Created August 18, 2020 14:07
Show Gist options
  • Save pasdam/ab3de134c4ff85f3ad4a5c56361a4748 to your computer and use it in GitHub Desktop.
Save pasdam/ab3de134c4ff85f3ad4a5c56361a4748 to your computer and use it in GitHub Desktop.
Script to connect to VPN with OTP on MacOS
#!/usr/bin/env bash
# CLI VPN connection for macOS
# Created to overcome macOS Mojave bug
# OSAScript "inspired" from https://github.com/alfredo/aws_vpn/blob/master/vpnconnection.scpt
CONFIG_FILE_PATH=$HOME/.vpn.mobileconfig
if [ ! -f $CONFIG_FILE_PATH ]; then
echo Download your .mobileconfig and save it as $CONFIG_FILE_PATH.
echo Eg. mv Downloads/[email protected] $CONFIG_FILE_PATH
exit 1
fi
vpn_names_list=($(cat $CONFIG_FILE_PATH | awk '{print $0;}' | grep -a -A1 UserDefinedName | grep string | cut -f 2 -d\> | cut -f 1 -d\< | tr ' ' _))
indexes=
if [ $# -lt 1 ]; then
echo Usage: $0 [VPN indexes] OTP
echo Eg: $0 0 1 123456
echo List of your VPNs and their IDs
echo ID\| "VPN Name"
for index in `seq 0 $((${#vpn_names_list[@]}-1))`; do
echo $index \| "${vpn_names_list[$index]}" "${vpn_host[index]}"
done
exit 2
elif [ $# -eq 1 ]; then
indexes=$(seq -s ' ' 0 1 $((${#vpn_names_list[@]}-1)))
else # $# > 1
indexes=${@:1:$#-1}
fi
vpn_otp=${@:$#}
for index in $indexes; do
vpnname=$(echo ${vpn_names_list[$index]}|tr _ ' ')
osx_vpn_name="${vpnname}, Not Connected"
echo "Connecting to: "$osx_vpn_name
osascript -e '
tell application "System Preferences"
reveal pane "Network"
activate
tell application "System Events"
tell process "System Preferences"
# Waits until Window 1 is fully loaded
repeat until exists window 1
end repeat
tell window 1
repeat with r in rows of table 1 of scroll area 1
if (value of attribute "AXValue" of static text 1 of r as string) is equal to "'"$osx_vpn_name"'" then
select r
tell group 1
click button "Authentication Settings…"
end tell
tell sheet 1
set focused of text field 2 to true
set value of text field 2 to "'"$vpn_otp"'"
click button "Ok"
end tell
click button "Apply"
delay 1
tell group 1
click button "Connect"
end tell
end if
end repeat
end tell
end tell
end tell
quit
end tell
'
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment