How to automatically connect VPN when connecting to a network?

In my university, the only way to access Internet is to connect to a VPN server. I've configured the VPN on my Mac and it's working fine, but I need to manually connect to the VPN every time I connect to the University network. How can I configure my Mac so it automatically uses the VPN whenever I'm working inside the University network?

Edit:
Can I use AppleScript to achieve this? Theoretically, it should be fairly simple, something like this:

if NetworkAPI.connectedNetwork.SSID == "Specific SSID":
    NetworkAPI.getVPNConnection("VPN Name").connect()

(I added AppleScript tag to my question to attract people with expertise in AppleScript, but any other method is acceptable.)


LifeHacker has answered your prayers (with Apple Script). You will obviously need to replace VPN University with the name of the service pertinent to you, and SSID University with the name of your university's SSID.

on idle
    set mySSID to do shell script "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'"
    if ((mySSID as string) is equal to "SSID University") then
    tell application "System Events"
            tell current location of network preferences
            set myConnection to the service "VPN University"
            if myConnection is not null then
                if current configuration of myConnection is not connected then
                    connect myConnection
                end if
            end if
        end tell
        return 120
    end tell
    end if
end idle

You can save this as an application any way you want, I prefer to go through Automator, though Script Editor, AppleScript, or XCode are also capable of compiling AppleScript, save it as an application, mark it to start on log in, then if you want to be fancy, you can either tell XCode not to have its icon on the dock, or edit the .plst file in the application bundle as such:

<key>LSUIElement</key>
<string>1</string>

This little hack per user ianneub.

Note I have tested the applescript piece only on my early '11 15" MBP OS X 10.10. Your mileage may vary if you're running El Capitan (I bet it doesn't though). This post comes with no warranties of any kind, and may give you gonorrhea.

EDIT: Note I updated the original script to check for a specific SSID, then perform the actions. I'm on my WinXP machine right now, so this is an untested, but relatively safe change. I found the info on getting the current SSID here and info on string comparison here.