Mac OS automatically changes network location based on WI-FI name
Last updated: 4 years ago
Mac OS provides us with a Network Location feature where we can set different DNS/VPN, etc. for different locations. However, every time our actual location changes, we have to manually switch. Since the DNS server I use at home is different from the one I use at work, I often find that I cannot connect to some internal networks when I’m at work, and only realize later that I forgot to switch locations!
I wonder if it’s possible to change this Location based on our geographical location. After Googling it, I found that it’s not possible. However, someone suggested another way to do it, which is to modify the Location based on the name of the WI-FI. Generally, the name of a WI-FI network doesn’t change frequently, so this is also an indirect way to meet this requirement.
The original open source project is located here。
Installation and Setup
Setting up is very simple.
- Install the script.
1 |
|
It will require you to enter your password. The locationchanger
script will be automatically installed in the /usr/local/bin
directory.
- Setup
If your location name is the same as your WIFI name (e.g. Location is home, and WIFI name is also home), you don’t need to set up anything and can use it directly.
If, like me, your location name is not the same as your WIFI name, or if multiple WIFI names correspond to the same location, you can follow my steps to set it up.
1 |
|
Modify the locations.conf
file and save it. For example:
1 |
|
The first part is the WI-FI name and the second part is the location name.
Switching logs will be written to the
~/Library/Logs/LocationChanger.log
file, and can be viewed with the following command.1
$ tail -f ~/Library/Logs/LocationChanger.log
Effect
Now let’s switch the WI-FI and see the effect.
Current
Switch the WI-FI.
I am connected to my phone’s Wi-Fi, which does not have a location configured, so it automatically switched to Automatic.
Check the logs:
1 |
|
Switch back:
1 |
|
Very convenient, no need to worry about forgetting to switch positions anymore~
More Features
In fact, the power of this script lies in listening to the system’s network switch event. Not only can it switch NetWork Location when switching, but it can also automatically run some custom scripts. The setup is just as simple.
For example, when I switch to the office
location, I want to turn on Dark Mode
, and when I’m at home
or other locations, turn off Dark Mode
.
All I need to do is add the following script to ~/.locations/office
:
1 |
|
Add the following script under ~/.locations/home
and ~/.locations/Automatic
:
1 |
|
Complete steps:
1 |
|
Then switch Wi-Fi and you should see the effect~
Finally, a mention of osascript
, a powerful command that comes with Apple and is worth learning more about.
Unless otherwise stated, all articles on this blog are written in CC BY-SA 4.0 , Please indicate the source when reproducing!