背景

我们一般使用 SS 做DL,虽然浏览器可以,但是终端不行。
因为在终端下不支持socks5DL,只支持httpDL,wget、curl、git、brew等命令行工具都会变得很慢。

苹果在新系统中加入了SIP安全机制
会阻止第三方程序向系统目录内(/System,/bin,/sbin,/usr(除了/usr/local))进行写操作,sudo也不行。
办法是先把SIP关了,等装好软件配置好后再打开SIP。或者改用其他软件。
因为懒得去把SIP关了开开了关了,找了另外一个软件privoxy。
它刚好就是安装在/usr/local内,不需要关闭SIP也可以正常使用。

方式一(终端支持socks5DL)

export http_proxy="socks5://127.0.0.1:1080"
export https_proxy="socks5://127.0.0.1:1080"
# or
export ALL_PROXY="socks5://127.0.0.1:1080"

在这里插入图片描述
这样只是在当前命令行生效,想永久生效将上面的文件写入到 .bashrc或者.zshrc

还可以在 ~/.bash_profile 加入开关函数,使用起来更方便。

function proxy_off(){
    unset http_proxy
    unset https_proxy
    echo -e "已关闭DL"
}

function proxy_on() {
    export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
    export http_proxy="socks5://127.0.0.1:1086"
	export https_proxy=$http_proxy
    echo -e "已开启DL"
}

function proxy_status() {
    echo $https_proxy
    curl cip.cc
}

在这里插入图片描述

方式二(终端不支持socks5DL)

privoxy 安装

brew install privoxy

privoxy 配置

vim /usr/local/etc/privoxy/config

底部加入

listen-address 0.0.0.0:8118
forward-socks5 / localhost:1086 .

第一行设置 privoxy 监听任意IP地址的8118端口。
第二行设置本地socks5DL客户端端口。这里要自己去看看
在这里插入图片描述

启动 privoxy

因为没有安装在系统目录内,所以启动时要打全路径。

sudo /usr/local/sbin/privoxy /usr/local/etc/privoxy/config
# 查看是否启动成功
netstat -na | grep 8118

使用 privoxy

export http_proxy='http://localhost:8118'
export https_proxy='http://localhost:8118'

原理是将 socks5 DL转化成 http DL给命令行终端使用。
取消

unset http_proxy
unset https_proxy

验证

curl cip.cc

在这里插入图片描述

curl https://www.google.com.hk/

在这里插入图片描述

Q&A

1、为什么terminal终端不能使用系统DL(WIFI网络设置中的HTTP,SOCKSDL设置)?
答:Shell 早于 macOS 并且有自己的配置DL规则。Shell 对系统偏好设置中的DL设置一无所知,需要单独配置。

2、为什么设置了http_proxy等环境变量,git, curl等命令行工具可以上网了?
答:git,wget, curl,brew等cli,甚至GCP提供的gcloud sdk内部都会读取http_proxy, https_proxy, all_proxy等系统环境变量:

仅仅是应用程序运行时环境变量,没有魔法。比如Node.js应用程序,可以使用process.env.http_proxy来读取程序运行时环境变量。其他语言比如Go, Java, Python, PHP都有各自的内置标准库API或全局变量(比如Node.js的process)来读取系统环境变量。git, wget, curl, brew, gcloud和我们自己写的应用程序一样,没什么特殊的。

node         
Welcome to Node.js v14.16.0.
Type ".help" for more information.
> process.env.http_proxy
'http://127.0.0.1:7890'

参考资料

https://double-c.github.io/2018/10/17/mac-ss-cmd/index.html
https://github.com/mrdulin/blog/issues/18
https://www.0x2beace.com/how-to-make-terminal-commands-go-through-proxy/

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐