Last active
April 11, 2022 10:11
-
-
Save akshayamaldhure/d209a0a9e0a317eeac7beaae8ccd7b85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# assumes lazy-connect CLI is installed and initialised on your Mac, but does not work well all the times :/ | |
# pre-requisite: grant Accessibility permission to the Apple Script under System Preferences -> | |
VPN_NAME="the-name-of-your-vpn-here" | |
VPN_IP="you-vpn-ip-here" # you can find this out from ifconfig when connected to the VPN, only first three decimal numbers from the IP are needed here. | |
function close_system_preferences() | |
{ # closes the System Preferences pane on Mac OS | |
echo "Closing the System Preferences pane" | |
osascript -e 'tell application "System Preferences" to close first window' | |
} | |
function is_vpn_connected() | |
{ # takes the IP of the VPN for which the connection status is to be checked | |
sleep 3 # as reflecting the IP in ifconfig may take some time | |
if ifconfig | grep -q "$1"; then | |
return 0 | |
else | |
return 1 | |
fi | |
} | |
function handle_preferences_error() | |
{ | |
osascript -e " | |
try | |
tell application \"System Events\" to tell process ¬ | |
\"System Preferences\" to click (buttons of sheet 1 of window 1 whose name is \"OK\") | |
on error errMsg | |
do shell script \"logger -t 'AS DEBUG' \" & errMsg | |
end try" | |
} | |
function connect_to_vpn() | |
{ # takes the name of the VPN to be connected to with lazy-connect CLI | |
if lazy-connect "$1" && sleep 5 && is_vpn_connected "$2" ; then | |
echo "Connected to the VPN $1 successfully using lazy-connect" | |
return 0 | |
else | |
echo "Could not connect to the VPN $1 using lazy-connect" | |
handle_preferences_error | |
close_system_preferences | |
return 1 | |
fi | |
} | |
close_system_preferences | |
if ! is_vpn_connected $VPN_IP ; then | |
echo "You are not connected to the VPN $VPN_NAME, trying to connect now" | |
vpn_connect_success=1 | |
retry_attempt=0 | |
MAX_RETRIES=5 | |
while [[ $vpn_connect_success && $retry_attempt != "$MAX_RETRIES" ]] ; do | |
if connect_to_vpn $VPN_NAME $VPN_IP ; then | |
vpn_connect_success=0 | |
exit 0 | |
else | |
echo "Retry attempt #${retry_attempt}" | |
retry_attempt=$((retry_attempt+1)) | |
fi | |
done | |
else | |
echo "You are already connected to the VPN $VPN_NAME" | |
exit 0 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment