AppleScript to display the VPN status bar area icon
I am trying to write an AppleScript to connect to a VPN service. Once connected to the VPN, I want to display the VPN icon in the status area of the menu bar.
I've gotten as far as
- connecting to VPN
- displaying the Network section of System Preferences
but I am unable to select the Service. How do I do that?
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.network"
tell application "System Events" to tell process "System Preferences" to tell window "Network"
-- code to select the VPN Service "XYZ" and click the "Show VPN Status in menu"
end tell
end tell
The answer to your question can be split in two parts:
-
connecting to a VPN is not a task that needs GUI scripting (i.e. open the network preferences pane and simulate a click on an item), as that functionality is part of the Network Preferences Suite of System Events since Leopard (I think). All you need is
tell application "System Events" tell current location of network preferences connect service "<name of your VPN>" end tell end tell
-
displaying the VPN status bar item however, is not part of the Network Preferences Suite. If you cannot live with the icon being present permanently in your status bar area, you will have to use GUI scripting to enable it on demand:
property vpnToUse : "<name of your VPN>" tell application "System Events" -- first activate the network pane, wait for it to load -- also might want to make sure this does not interrupt user interaction <your code here> -- get the index of the VPN in the service list tell current location of network preferences repeat with i from 1 to (count of every service) if name of (service i) is vpnToUse then set listIndex to i exit repeat end if end repeat end tell -- select the VPN item in the service list and activate status bar item tell process (name of application id "com.apple.systempreferences") tell window 1 select row listIndex of table 1 of scroll area 1 tell checkbox 1 of group 1 -- only click if not already activated if value is 0 then click it end tell end tell end tell end tell
note this part, as always in GUI scripting, is potentially highly disruptive: it steals focus from the user, in the worst case even canceling whatever she was doing if she happened to be using System Preferences (there is an excellent discussion on the pros and cons of GUI scripting to manipulate System Settings predating the Preferences Suites at MacScripter). It’s also brittle (as it is subject to the specific UI layout of the preferences pane), although if you follow the model I show above, using indexes and process name retrieval via the application ID, it will at least not be affected by localization issues.