Macos – How to you automatically run a script after connecting to a VPN on OS X

macosscriptvpn

I have configured the VPN connection in OS X 10.7.3, but since the network I'm connecting to uses a corporate proxy, has custom Maven repository servers, and other network-specific settings (remote drives, for instance), I want to run a script on logon/logoff of a VPN to:

  • change the Maven ~/.m2/settings.xml to point to their maven repo
  • map a few smb:// shares,
  • alias some commands to use their servers

I don't know how to accomplish this, though.

  1. How do you execute a script or set of commands automatically on logon?
  2. How do you execute a script or set of commands automatically on logoff?

Best Answer

If you already have the VPN configured, you can connect to it via commandline. As I explained in this answer, you can create two shell functions for login and logout, respectively, by adding them to your ~/.bash_profile – see the linked answer for the vpn-disconnect function.

function vpn-connect {
/usr/bin/env osascript <<-EOF
tell application "System Events"
        tell current location of network preferences
                set VPN to service "UniVPN" -- your VPN name here
                if exists VPN then connect VPN
        end tell
end tell
EOF 
# insert your commands here
}

Just include the custom commands you need after the EOF marker.


If you want a GUI way to do it, open up Automator.app and create a new Application. Then, drag the actions to run an AppleScript and Shell script from the left pane, and insert the commands as shown below.

You can then just put this pseudo-application into your Dock to quickly launch it.