目录
问题描述
作者在使用wsl2下的Ubuntu开发,克隆仓库时遇到报错,"Failed to connect to github.com port 443 after 21068 ms: Could not connect to server",尝试过检查网络连接,关闭防火墙,更换DNS,更改hosts文件,使用vpn等多种手段,但都没成功。
最终决定使用SSH协议替代HTTPS,一次成功。
Windows解决方案
首先你需要一个github账号。记住你的账号邮箱。在Powershell输入命令
ssh-keygen -t ed25519 -C "你的邮箱地址"
这是一个用于生成SSH私钥与公钥——密钥对的命令。 文件路径~/ .ssh。在Powershell输入命令
cd ~/.ssh
ls
我们需要公钥,查看公钥内容。(带pub的是公钥)
cat id_ed25519.pub
输出内容类似ssh-ed25519 AAAAB3NzaC1yc2E......复制这段内容,粘贴到Github的SSH Keys 设置中。
测试SSH连接
ssh -T git@github.com
若成功便会显示 Hi XXX! You've successfully authenticated...
但是如果出现如下错误,则是22端口被阻止。需要修改或创建 ~/ .ssh/config 文件
ssh: connect to host github.com port 22: Connection refused
#打开或创建config文件
notepad $HOME\.ssh\config
#添加如下内容
Host github.com
Hostname ssh.github.com
Port 443
User git
注意保存时文件名必须是config而不是config.txt 等!
成功后,将git clone 命令从 HTTPS 改为 SSH 协议即可
#原命令
git clone https://github.com/xxx/xxx.git
#更改后命令
git clone git@github.com:xxx/xxx.git
WSL2解决方案
由于wsl2可以直接访问Windows文件系统,所以可以直接复用已有密钥。Linux 系统对 SSH 配置文件的权限和所有权有严格限制,需要额外设置文件权限。
# 在 WSL2 的 Ubuntu 终端中操作
# 创建 .ssh 目录(如果不存在)
mkdir -p ~/.ssh
# 将 Windows 的 SSH 密钥复制到 WSL2
# 将 name 替换为你的 Windows 用户名
cp /mnt/c/Users/name/.ssh/id_ed25519 ~/.ssh/id_ed25519
cp /mnt/c/Users/name/.ssh/id_ed25519.pub ~/.ssh/id_ed25519.pub
cp /mnt/c/Users/name/.ssh/config ~/.ssh/config
# 设置文件权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 600 ~/.ssh/config
#测试是否连通
ssh -T git@github.com
成功显示与Windows中的相同