2

Question: Is there a way to configure a LaunchAgent to start (and keep alive) a script when entering a specific location?

Example: When switching to the location "Office" i want to trigger a LaunchAgent that starts a script which opens a SSH tunnel that i need.

Hennes
  • 65,804
  • 7
  • 115
  • 169
lajuette
  • 4,852

1 Answers1

2

Mac OS X updates a file in /Library/Preferences/SystemConfiguration/ called preferences.plist. It updates a key called CurrentSet to the UUID of the current location (each location is given a UUID when it is created.) You can determine the name of that Location by looking for the UserDefinedName key in the dictionary with the same name as the UUID.

Example Script:

#! /bin/bash

# Proof of Concept Script to check if the location changed.

CURRENT_LOCATION=`/usr/libexec/PlistBuddy -c "Print :CurrentSet" /Library/Preferences/SystemConfiguration/preferences.plist | sed 's/\/Sets\///'`
CURRENT_LOCATION_NAME=`/usr/libexec/PlistBuddy -c "Print :Sets:$CURRENT_LOCATION:UserDefinedName" /Library/Preferences/SystemConfiguration/preferences.plist`

# If location is the one we want:
# Logger puts the message into syslog

if [ $CURRENT_LOCATION_NAME == "Office" ]; then
    logger "`date` => In the Office"

    #Commands to set up SSH Tunnel among others

else
# If the location is not the one we want: Undo whatever we have done.
    logger "`date` => Out of Office"

    #Commands here for when you leave the office location
fi

Example LaunchAgent to run above script whenever the location is changed:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>local.IDENTIFIER_HERE.SOMETHING</string>
    <key>OnDemand</key>
    <true/>
    <key>Program</key>
    <string>/PATH/TO/SCRIPT</string>
    <key>WatchPaths</key>
    <array>
        <string>/Library/Preferences/SystemConfiguration/preferences.plist</string>
    </array>
</dict>
</plist>

Fill in the path to the script, give it an identifier and save it with the same name (eg. local.lajuette.location should be a file named local.lajuette.location.plist). Copy this file to ~/Library/LaunchAgents and run launchctl load ~/Library/LaunchAgents/name.of.plist.here.plist. With the sample files open up Console.app and check for the line: "DATE => In the Office" or "DATE => Out of Office" accordingly.

You may want to check out: How can I get a script to run every day on Mac OS X for more info on how to load and run your script using launchd if you're not sure.

Chealion
  • 26,327