出于众所周知的原因,我们经常需要通过代理连接到 github.com

我们已经很熟悉在浏览器中使用代理,但在 Linux 命令行中,有时并不那么顺利。

Git 通常通过 SSH 或 HTTP 连接远程仓库。

如果在 Git 仓库中查看远程地址:

1
2
3
$ git remote -v
origin  [email protected]:example/example.git (fetch)
origin  [email protected]:example/example.git (push)

而非:

1
https://github.com/example/example.git

那么 Git 将通过 SSH 连接 github.com

此时,直接在 Git 中设置 HTTP 代理,对通过 SSH 执行的 git pushgit pull 等命令无效:

1
2
3
git config --global http.proxy http://your_proxy_url
git config --global --unset http.proxy
git -c http.proxy=http://server:port push

当然,可以修改远程仓库地址来解决此问题;也可以修改 SSH 配置。

编辑 ~/.ssh/config

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/your_private_key
  ProxyCommand nc -x your_proxy_url:your_proxy_port %h %p

修改后会立刻生效。

此时将通过 SOCKS5 代理连接至 github.com

或者,通过 HTTP 代理:

ProxyCommand corkscrew your_proxy_url your_proxy_port %h %p

注意,ProxyCommand nc -x your_proxy_url:your_proxy_port %h %p 使用了 Netcat 的 nc 命令。请根据所用发行版自行安装 Netcat。

在 Arch Linux 中有 extra/gnu-netcatextra/openbsd-netcat,请使用后者。