Chrizzldi Chrizzldi - 3 months ago 19
AppleScript Question

Handle VPN Connections via AppleScript

In order to keep my VPN connection active, i wrote this little applescript:

tell application "System Events"
tell network preferences
connect service "VPNServiceNameIConfigured"
end tell
end tell


This script works fine!
I wrote myself a lauchdeamon .plist to call the script on StartUp, WakeUp and every 5 seconds. This means, that every time my vpnconnection breaks, it will be automatically reconnected (if possible) every 5 seconds.

This part works fine but i want to improve it a little. I want to use a if-case like

if network preferences service "VPNServiceNameIConfigured" is not connected
connect it
else do nothing


Is there a way to do that? If so i am very happy about an example or good documentation using applescript for handling system events.

Thank you!

Answer

The place to look for that information is in the Dictionary for System Events. You can open any dictionary using “Open Dictionary…" in AppleScript Editor’s File menu.

You don’t give enough information to write exact code; for example, does your VPNServiceNameIConfigured service contain any configurations?

If you can get a configuration, you should be able to check the “connected” of that configuration. Something like:

if connected of current configuration of service VPNServiceNameIConfigured is false then
    connect it
end if

Depending on your setup, you might also be able to check the “active” boolean of service VPNServiceNameIConfigured. Here’s a simple test script that works on my setup to check that my WiFi is active:

tell application "System Events"
    tell network preferences
        set myConnection to location "Automatic"
        --get name of every service of myConnection
        set myService to service "Wi-FI" of myConnection
        --get properties of myConnection
        if active of myService is false then
            display dialog "Need to reconnect"
        end if
    end tell
end tell

The “connected” boolean is only available on a configuration, however, and that may be your more reliable option, if your service contains a configuration.

Comments