chauncey-garrett
5/4/2013 - 2:37 PM

vpn-utilities.applescript

-- Author: Michael Bianco <http://mabblog.com/>
-- Some help from: http://discussions.info.apple.com/message.jspa?messageID=10363317

on create_vpn_service(vpn_name)
	tell application "System Preferences"
		reveal pane "com.apple.preference.network"
		activate
		
		tell application "System Events"
			tell process "System Preferences"
				tell window 1
					click button 10 -- "Add Service"
					tell sheet 1
						-- set location type
						click pop up button 1
						click menu item "VPN" of menu 1 of pop up button 1
						delay 1
						
						-- set connection type
						click pop up button 2
						click menu item "PPTP" of menu 1 of pop up button 2
						delay 1
						
						-- set name of the service
						-- for some reason the standard 'set value of text field 1' would not work
						set value of attribute "AXValue" of text field 1 to vpn_name
						click button 1 -- "Create"
					end tell
					click button 7 -- "Apply"
				end tell
			end tell
		end tell
	end tell
end create_vpn_service

on update_vpn_settings(vpn_name, vpn_address, vpn_username, vpn_password)
	tell application "System Preferences"
		reveal pane "com.apple.preference.network"
		activate
		
		tell application "System Events"
			tell process "System Preferences"
				tell window 1
					-- select the specified row in the service list 
					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) contains vpn_name then
							select r
						end if
					end repeat
					
					-- set the address & username / account name
					-- note that this is vpn specific
					tell group 1
						set value of text field 1 to vpn_address
						set value of text field 2 to vpn_username
						click button 2 -- "Authentication Settings…"
					end tell
					
					-- open up the auth panel and set the login password
					tell sheet 1
						set value of text field 1 to vpn_password
						click button 1 -- "Ok"
					end tell
					
					click button 7 -- "Apply"
				end tell
			end tell
		end tell
	end tell
end update_vpn_settings

on vpn_exists(vpn_name)
	tell application "System Events"
		try
			service vpn_name of network preferences
			return true
		on error
			return false
		end try
	end tell
end vpn_exists

on vpn_status(vpn_name)
	tell application "System Events"
		return connected of configuration of service vpn_name of network preferences as boolean
	end tell
end vpn_status

on toggle_vpn_status(vpn_name)
	-- note that this function assumes that the vpn exists
	tell application "System Events"
		-- if kind of service = 14 then vpn
		
		set s to service vpn_name of network preferences
		if not connected of configuration of s as boolean then
			tell s to connect
		else
			tell s to disconnect
		end if
	end tell
end toggle_vpn_status