把下面的 shell 脚本保存到一个文件:
set_proxy.sh```shell
#!/bin/bash
function scutil_query {
key=$1
scutil <<EOT
open
get $key
d.show
close
EOT
}
SERVICE_GUID=$(scutil_query State:/Network/Global/IPv4 | grep "PrimaryService" | awk '{print $3}')
currentservice=$(scutil_query Setup:/Network/Service/$SERVICE_GUID | grep "UserDefinedName" | awk -F': ' '{print $2}')
set_proxy() {
http=$1
socks=$2
if [[ -z $http ]] && [[ -z $socks ]]; then
return 0
fi
# http 代理
if [[ ! -z $http ]]; then
networksetup -setwebproxystate "$currentservice" on
networksetup -setsecurewebproxystate "$currentservice" on
hostname=$(echo "$http" | awk -F ':' '{print $1}')
port=$(echo "$http" | awk -F ':' '{print $2}')
networksetup -setwebproxy "$currentservice" $hostname $port
networksetup -setsecurewebproxy "$currentservice" $hostname $port
fi
# socks 代理
if [[ ! -z $socks ]]; then
networksetup -setsocksfirewallproxystate "$currentservice" on
hostname=$(echo "$socks" | awk -F ':' '{print $1}')
port=$(echo "$socks" | awk -F ':' '{print $2}')
networksetup -setsocksfirewallproxy "$currentservice" $hostname $port
networksetup -setsocksfirewallproxy "$currentservice" $hostname $port
fi
# 设置代理绕过的域名
networksetup -setproxybypassdomains "$currentservice" 192.168.0.0/16 10.0.0.0/8 172.16.0.0/12 127.0.0.1 localhost "*.local"
timestamp.apple.com}
# 取消代理设置
unset_proxy() {
networksetup -setwebproxy "$currentservice" "" "" off "" ""
networksetup -setsecurewebproxy "$currentservice" "" "" off "" ""
networksetup -setsocksfirewallproxy "$currentservice" "" "" off "" ""
networksetup -setwebproxystate "$currentservice" off
networksetup -setsecurewebproxystate "$currentservice" off
networksetup -setsocksfirewallproxystate "$currentservice" off
networksetup -setproxybypassdomains "$currentservice" Empty
}
if [[ $1 == "http" ]]; then
set_proxy $2 ""
elif [[ $1 == "socks" ]]; then
set_proxy "" $2
else
unset_proxy
fi
```
使用:
```shell
bash
set_proxy.sh http 127.0.0.1:10086 # 设置 http 和 https 代理
bash
set_proxy.sh socks 127.0.0.1:10086 # 设置 socks5 代理
bash
set_proxy.sh # 恢复
```