Git配置代理实现加速
本地开启 VPN 代理后,Git 也需要设置代理。否则就会出现能访问 GitHub 网站,但是 git push 超时等情况。
- 设置全局 http/https 代理
# 不同代理的端口号不一样
git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy https://127.0.0.1:7890
# 或者有时候
git config --global http.proxy 'socks5://127.0.0.1:7890'
git config --global https.proxy 'socks5://127.0.0.1:7890'- 取消全局 http/https 代理(如果不用 VPN,记得取消代理)
git config --global --unset http.proxy
git config --global --unset https.proxy- 设置 ssh 代理,需要新建并配置一个
config。- linux、MacOS系统:~/.ssh/config
- Windows系统:C:/Users/用户名/.ssh/config
在SSH连接时,这个配置文件通常被用来设置主机别名、指定用户和身份验证方法等。
Host example.com # 主机别名
HostName example.com # 主机名
User username # 用户名
IdentityFile ~/.ssh/id_rsa # 身份验证方法
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_rsa
Host gitee.com
HostName gitee.com
User git
IdentityFile ~/.ssh/gitee_rsa 一个详细的基于自己的代理案例
# Windows,注意替换端口号和 git\mingw64\bin\connect.exe 的路径
ProxyCommand "D:\Program Files\Git\mingw64\bin\connect" -S 127.0.0.1:7890 -a none %h %p
# MacOS,注意替换端口号
ProxyCommand /usr/bin/nc -v -x 127.0.0.1:7890 %h %p
# 备用主机名
Host github.com
Hostname ssh.github.com
User git
Port 443
TCPKeepAlive yes
IdentityFile "C:\Users\用户名\.ssh\id_rsa"
# 备用主机名
Host gitlab.com
Hostname altssh.gitlab.com
User git
Port 443
PreferredAuthentications publickey
IdentityFile "C:\Users\用户名\.ssh\id_rsa"需要注意的是,如果使用 HTTPS 协议可能更加稳定,可以尝试使用HTTPS 协议进行连接。
ssh.github.com 是 Github 的 SSH 代理服务器地址。当你在使用 Git 命令或者其他 Git 工具时,如果直接连接 Github 的 SSH 服务github.com,可能会因为网络限制或其他原因导致连接失败。为了解决这个问题,Github 提供了一个 SSH 代理服务器ssh.github.com,可以通过这个代理服务器来连接 Github 的 SSH 服务。
保存后 config 文件后测试方法如下,返回 successful 或者 welcome 之类的就成功了。(需要保证已经讲SSH公钥添加到托管平台)
# 测试是否设置成功
ssh -T git@github.com
ssh -T git@gitlab.com测试成功后会在~/.ssh 生成known_hosts。known_hosts 是 SSH 客户端用来记录远程 SSH 服务器的公钥指纹的文件。在 SSH 连接建立时,客户端会检查该文件中是否存在远程主机的公钥指纹。如果公钥指纹匹配,则说明远程主机是可信的,客户端会接受连接并建立 SSH 会话。如果公钥指纹不匹配,则说明远程主机的身份可能受到篡改或欺骗,客户端会拒绝连接并给出警告信息,以防止中间人攻击。
当第一次连接到一个新的 SSH 服务器时,SSH 客户端会自动将该服务器的公钥指纹保存到 known_hosts 文件中。这样,在以后的连接中,客户端就可以比较该服务器的公钥指纹和 known_hosts 文件中的记录来验证服务器的身份。该文件的格式是每行一个记录,其中包含了远程服务器的 IP 地址、公钥指纹以及可选的注释信息。在一些情况下,如果你不想保存某个主机的公钥指纹,你可以手动编辑 known_hosts 文件并删除相应的记录。
参考链接: