让终端命令请求走 Charles 或 SS 代理的方法
前言
最近需要用终端 CocoaPods 命令在外网下载安装第三方库,所以需要进行下载。但是下载速度非常的慢,有时还会下载超时,所以就想到用代理的方式进行下载。
目前有两种方案:
方案一:通过 Charles 进行重定向进行下载;(已验证,可行)
方案二:通过 SS 代理直接下载;
研究发现终端使用 curl 进行网络请求,但是 curl 方式不走代理,所以需要设置终端代理。
终端中网络请求可能对应以下协议类型,具体问题要具体分析,同时不同协议走代理的配置方式不同。
Git download 可能对应的请求协议类型(http(s)://、git://、ssh://等), eg:1
2
3$ /usr/bin/git clone https://github.com/xx
or
$ /usr/bin/git clone git://github.com/xx
Http download 对应请求类型可能是 http(s):// ,eg:1
$ /usr/bin/curl http(s)://xxx.xx/xxx
Charles
1 | -> Installing MobileVLCKit (3.1.5) |
查看当前终端窗口的代理1
2$ echo $http_proxy //查看 http 代理
$ echo $https_proxy //查看 https 代理
因为有 http 和 https 区分,所以有时需要执行的命令就不一样啦,系统代理一般格式为 http(s)_proxy=http://proxyAddress:port
,本地代理 proxyAddress 一般为 127.0.0.1 或 localhost。因为 Charles 设置的代理端口为 8888,所以这里 port 为 8888,具体要看设置。
在当前终端设置代理:1
2
3$ export https_proxy=http://127.0.0.1:8888
or
$ export http_proxy=http://127.0.0.1:8888
取消当前终端代理设置:1
2
3$ unset http_proxy
或:
$ unset https_proxy
如果能够修改 curl 请求的话,也可以试试下面的方法:
cURL和libcurl
对于命令行上的cURL:
curl –proxy localhost:8888如果您正在使用libcurl开发应用程序,则可以将其配置为使用Charles作为其代理服务器:
curl_easy_setopt(pCurl,CURLOPT_PROXY,“127.0.0.1”);
curl_easy_setopt(pCurl,CURLOPT_PROXYPORT,8888);如果您使用SSL,则可能希望在开发期间禁用证书验证,如果您无法获得cURL以信任Charles的CA证书:
curl_easy_setopt(pCurl,CURLOPT_SSL_VERIFYPEER,0);
感谢Michael Klische提供此信息。
参考资料
SS
若在当前终端运行以下命令,那么 wget、curl、http(s) 这类网络命令都会经过 SS 代理:1
$ export ALL_PROXY=socks5://127.0.0.1:1080
或 仅设置 http(s) 协议代理1
2$ export https_proxy=socks5://127.0.0.1:1080
$ export http_proxy=socks5://127.0.0.1:1080
上面的 SS 方法足以应对日常需要,如果有兴趣的同学可以分别对 Git 传输协议研究一下。
Git
让 Git 走 SS 代理,加速下载速度,首先我们来了解一下支持 Git 传输的协议。
Git 可以使用四种主要的协议来传输数据:本地传输、SSH 协议、Git 协议和 HTTP 协议。
本地协议:1
2
3$ git clone /opt/git/prosect.git
or
$ git clone file:///opt/git/project.git
SSH 协议:1
2
3$ git clone ssh://user@server/project.git
or
$ git clone user@server:project.git
Git 协议:(待完善,可以将 git:// 改为 https:// 进行代理)
HTTP/S 协议:1
$ git clone http(s)://example.com/gitproject.git
其代理配置各不相同:core.gitproxy 针对 git:// 协议,http.proxy 针对 http:// 协议,ssh:// 协议的代理需要配置 ssh 的 ProxyCommand 参数。
HTTP/S 协议方式
针对 http(s) 协议进行全局配置,去掉 --global
只对此项目有效。1
2
3
4
5$ git config --global http.proxy 'socks5://127.0.0.1:1080'
$ git config --global https.proxy 'socks5://127.0.0.1:1080'
or
$ git config http.proxy 'socks5://127.0.0.1:1080'
$ git config https.proxy 'socks5://127.0.0.1:1080'
取消配置1
2git config --global --unset http.proxy
git config --global --unset https.proxy
SSH 协议方式
打开 ~/.ssh/config
添加以下配置:1
2Host github.com
ProxyCommand nc -X 5 -x 127.0.0.1:1080 %h %p
或
直接在命令行中输入 ssh -o ProxyCommand="nc -X 5 -x 127.0.0.1:1080 %h %p" [-p hostPort] root@address
Git 协议方式
待验证1
$ git config core.gitproxy 'socks5://127.0.0.1:1080'
or 可以借助 ssh 协议 eg:git config --add core.gitproxy '"proxy-command" for example.com'
1
$ git config core.gitproxy '"ssh" for github.com'
有兴趣的同学可以研究一下git-config - Get and set repository or global options
参考资料
参考资料
文档信息
- 版权声明:自由转载-保持署名-非商用-非衍生 ( CC BY-NC-ND 4.0 )