Background
At Rocketium, developers have to use two different VPN connections based on what they are working on. We can connect directly from the network tab in the status bar. But developers tend to forget to change VPN before SSH into the machine. They are a couple of ways to solve this. In this post, i will show how to automate VPN connection using OSA Script.
Prerequisite
VPN has to be configured in MacOSX network preference and knowledge on osascript.
Let’s Build
First, we connect to our VPN and then SSH into the machine.
Automating VPN connection
For this, we are using the apple script. In this script, we tell OSX to connect to System Preferences → Network. Now we will iterate through the pre-configured row and select our VPN and then connect our VPN. Here is the script
repeat while true
tell application "System Events"
tell application process "System Preferences"
if not (window 1 exists) then
tell application "System Preferences"
activate
end tell
repeat while not (menu bar 1 exists)
end repeat
repeat while not (menu "System Preferences" of menu bar 1 exists)
end repeat
repeat while not (menu item "Hide System Preferences" of menu "System Preferences" of menu bar 1 exists)
end repeat
delay 3
click menu item "Hide System Preferences" of menu "System Preferences" of menu bar 1
end if
click menu item "Network" of menu "View" of menu bar 1
tell window 1
repeat while not (rows of table 1 of scroll area 1 exists)
end repeat
repeat with current_row in (rows of table 1 of scroll area 1)
if value of static text 1 of current_row contains "VPN Name" then
select current_row
exit repeat
end if
end repeat
repeat with current_button in (buttons in group 1)
if name of current_button is equal to "Connect" then
click current_button
exit repeat
end if
end repeat
end tell
end tell
end tell
delay 60
end repeat
Replace VPN Name with your name.
Now we can put the above script and ssh address into a single utility file to make this process seamless.
ConnectAndSSH.sh
osascript -e 'tell app "Terminal" to do script "sleep 25; ssh -i sshPemFile username@ip"';
osascript /Users/gowthamkosaraju/Desktop/VPNAutomationScript.scpt;
In the above script, we said the terminal app to open a new window to sleep for 25 seconds and then SSH into the machine. Meanwhile, our VPNAutomation.scpt file will execute and VPN will be connected.
Since most of the developers work terminal app. It wouldn’t be amazing if we can do all these through a single command?
Let us use our favorite alias commands to do it. Go to the terminal app and type
vim ~/.zshrc
alias connectVPN=”/Users/gowthamkosaraju/Desktop/ConnectAndSSH.sh”
Reload your terminal app to make these changes effect. Now if you type connectVPN. You will connect to VPN and ssh into your machine with a single command.
Top comments (0)