My MacBook travels a lot and thus connects to various networks. Depending on the network it's connected to, I want it to start and stop some applications like a VPN client or instant messenger. As we have launchd and as all system configuration is a bunch of plist (read: plain xml) files located in /Library/Preferences/SystemConfiguration, we can easily script that:
#!/bin/sh msg="" if ifconfig | grep -q "inet 10.0.23."; then # at work, stop VPN to corporate network, start IM echo 'tell application "VPN CLIENT" to quit' | osascript echo 'tell application "Adium" to launch' | osascript msg="Stopped VPN CLIENT, started Adium" elif ifconfig | grep -q "inet 172.17.0."; then # at home echo 'tell application "VPN CLIENT" to launch' | osascript echo 'tell application "Adium" to launch' | osascript msg="Started VPN CLIENT, started Adium" elif ifconfig | grep -q "inet 212.62.64."; then # at some fancy customer echo 'tell application "VPN CLIENT" to launch' | osascript echo 'tell application "Adium" to quit' | osascript msg="Started VPN CLIENT, stopped Adium" else msg="Nothing to do" fi logger -t "$0" "$msg"
chmod 0755 ~/.syschange.sh
<?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>YOURNAME.SysChange</string> <key>ProgramArguments</key> <array> <string>/Users/YOURNAME/.syschange.sh</string> </array> <key>WatchPaths</key> <array> <string>/Library/Preferences/SystemConfiguration</string> </array> </dict> </plist>Of course you have to replace YOURNAME with your name. The Label can be more sophisticated, e.g. com.YOURDOMAINNAME.tools.SysChange.
launchctl load /Users/YOURNAME/Library/LaunchAgents/SysChange.plist