MacOS 15 下根据SSID自动切换位置

0
(0)
#!/bin/bash

# This script changes network location based on the name of Wi-Fi network.

exec 2>&1 >> $HOME/Library/Logs/LocationChanger.log

sleep 3

ts() {
    date +"[%Y-%m-%d %H:%M] $*"
}

ID=`whoami`
ts "I am '$ID'"

SSID=`system_profiler SPAirPortDataType | awk '/Current Network/ {getline;$1=$1;print $0 | "tr -d ':'";exit}'`

LOCATION_NAMES=`scselect | tail -n +2 | cut -d \( -f 2- | sed 's/)$//'`
CURRENT_LOCATION=`scselect | tail -n +2 | egrep '^\ +\*' | cut -d \( -f 2- | sed 's/)$//'`

ts "Connected to '$SSID'"

CONFIG_FILE=$HOME/.locations/locations.conf
ts "Probing '$CONFIG_FILE'"

if [ -f $CONFIG_FILE ]; then
    ts "Reading to '$CONFIG_FILE'"
    ESSID=`echo "$SSID" | sed 's/[.[\*^$]/\\\\&/g'`
    NEW_SSID=`grep "^$ESSID=" $CONFIG_FILE | cut -d = -f 2`
    if [ "$NEW_SSID" != "" ]; then
        ts "Will switch the location to '$NEW_SSID' (configuration file)"
        SSID=$NEW_SSID
    else
        ts "Will switch the location to '$SSID'"
    fi
fi

ESSID=`echo "$SSID" | sed 's/[.[\*^$]/\\\\&/g'`
if echo "$LOCATION_NAMES" | grep -q "^$ESSID$"; then
    NEW_LOCATION="$SSID"
else
    if echo "$LOCATION_NAMES" | grep -q "^Automatic$"; then
        NEW_LOCATION=Automatic
        ts "Location '$SSID' was not found. Will default to 'Automatic'"
    else
        ts "Location '$SSID' was not found. The following locations are available: $LOCATION_NAMES"
        exit 1
    fi
fi

if [ "$NEW_LOCATION" != "" ]; then
    if [ "$NEW_LOCATION" != "$CURRENT_LOCATION" ]; then
        ts "Changing the location to '$NEW_LOCATION'"
        scselect "$NEW_LOCATION"
        SCRIPT="$HOME/.locations/$NEW_LOCATION"
        if [ -f "$SCRIPT" ]; then
            ts "Running '$SCRIPT'"
            "$SCRIPT"
        fi
    else
        ts "Already at '$NEW_LOCATION'"
    fi
fi

这个脚本会需要你输入密码。自动将locationchanger脚本安装到了/usr/local/bin目录。

如果你的位置名称WIFI名称一致(如 Localtion 是 home, WIFI 名字也是 home),不用设置你直接都可以使用了。

如果你和我一样,位置的名称与 WIFI 名称并不一致,或者多个 WIFI 对应于同一个位置,你可以跟着我设置一下。

$ mkdir ~/.locations
$ touch ~/.locations/locations.conf

修改lcoations.conf文件,并保存。如:

XIAOMI-WIFI=home
TWWORK=office
# 查看日志
tail -f ~/Library/Logs/LocationChanger.log


这篇文章有用吗?

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

很抱歉,这篇文章对您没有用!

让我们改善这篇文章!

告诉我们我们如何改善这篇文章?


了解 工作生活心情记忆 的更多信息

订阅后即可通过电子邮件收到最新文章。

分类: