在使用 Git 进行版本控制时,有时我们会遇到以下错误提示:
Cloning into 'App'...
ssh: connect to host github.com port 22: Connection timed out
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.首先,通过 SSH 测试是否能成功连接到 GitHub。可以使用以下命令:
ssh -T git@github.com如果连接不成功,你可能会看到如下报错:
ssh: connect to host github.com port 22: Connection timed out
fatal: Could not read from remote repository.如果是这种情况,你可以尝试使用 ping github.com 来检测网络是否通畅。如果你在国内,可能需要使用代理(如全局代理 Tun)来解决网络问题。

Permission Denied (publickey) 错误解析如果你遇到 Permission denied (publickey) 错误,通常意味着 GitHub 没有正确识别你的 SSH 密钥。这个问题通常是由于 SSH 密钥没有正确配置或没有被添加到 GitHub 账户导致的。接下来我们来一步步解决。
查看是否有 SSH 密钥:
打开 C:\Users\xxxx\.ssh 目录,检查是否有 id_rsa 和 id_rsa.pub 文件。如果这些文件已经存在,说明你已有 SSH 密钥。否则,你需要生成一个新的 SSH 密钥对。
生成新的 SSH 密钥:
如果你没有现成的 SSH 密钥,可以通过以下命令生成新的密钥对:
ssh-keygen -t rsa -b 4096 -C "xxxxxxxxx.com"这时系统会提示你选择密钥的存储位置,通常按 Enter 选择默认路径(~/.ssh/id_rsa)。你也可以设置密钥密码,或者直接按 Enter 跳过此步骤。

生成 SSH 密钥后,你需要将公钥添加到 GitHub 才能正常进行身份验证。
id_rsa.pub 文件,复制其中的公钥内容(以 ssh-rsa 开头,以你的电子邮件结尾)。

完成公钥添加后,使用以下命令再次测试 SSH 连接:
ssh -T git@github.com如果一切顺利,你应该看到如下信息:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.此时说明 SSH 配置成功,可以进行 Git 操作了。

如果你有多个 SSH 密钥,你可能需要显式指定要使用的密钥。可以使用以下命令来指定:
ssh -i ~/.ssh/id_rsa -T git@github.comgit clone按照上述步骤操作后,重新运行 git clone 命令,此时应该能够正常克隆仓库:
git clone git@github.com:username/repository.git此时,Git 连接应该没有问题,并且可以顺利完成上传和下载操作。

通过以上步骤,解决了 GitHub 的 Permission denied (publickey) 错误。主要步骤包括生成 SSH 密钥、将公钥添加到 GitHub 账户以及测试 SSH 连接等。按照这些操作后,你应该能够顺利使用 SSH 协议进行 Git 操作。