How to auto switch DNS settings while connect to different WiFi?

You do not need to use a third-party application to accomplish your goal.

When Wi-Fi connects to a network the following file, among others, is modified:

/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist

You can use a User Launch Agent with a WatchPaths key to know when the target file is modified and execute your script accordingly.

The following is an example of how to accomplish the goal and is using SkyNet as the SSID of the Wi-Fi network.

Using networksetup to get the current Wi-Fi network, the following example shell script code is used and saved as e.g. /usr/local/bin/detect-wifi-change:

#!/bin/bash

[[ $(networksetup -getairportnetwork en0) == "Current Wi-Fi Network: SkyNet" ]] && say "connected to skynet"

In the example code above, when Wi-Fi is connected to SkyNet it simply says it's "connected to skynet", and you would replace SkyNet in the $(...) portion of the command with your target SSID, and replace the say "connected to skynet" command with the networksetup -switchtolocation Home command as shown in your question.

For the Launch Agent, in the Library of your Home folder you'd use the following example, saved as, e.g., ~/Library/LaunchAgents/com.my.detect.wifi.change.plist:

<?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>com.my.detect.wifi.change</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>/usr/local/bin/detect-wifi-change</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist</string>
    </array>
</dict>
</plist>

After saving the PLIST file, use launchctl to load it, e.g.:

launchctl load ~/Library/LaunchAgents/com.my.detect.wifi.change.plist

Note: You can use the unload verb with launchctl to unload the target PLIST file.

Now whenever Wi-Fi connects to a different SSID the e.g. /usr/local/bin/detect-wifi-change is executed and if connected to the target SSID the command after the && is executed.


Note: The above example was tested and worked under macOS High Sierra using my actual SSID in place of SkyNet in both places in the script.


 

Related Documentation:

In Terminal, substitute command for one of the following:

  • launchd
  • launchd.plist
  • launchctl

You can read the manual page for command in Terminal by typing command and then right-click on it and select: Open man Page

See Also:

  • A launchd Tutorial
  • Daemons and Services Programming Guide
  • Technical Note TN2083 Daemons and Agents

Keyboard Maestro can do this very easily:

Screenshot of Keyboard Maestro

Set the SSID and Location that you want, and that should do what you want.