git配置公钥/密钥

遇到 "git@github.com: Permission denied (publickey)" 错误通常意味着你尝试通过 SSH 连接到 GitHub 时,SSH 密钥没有被正确设置或者 GitHub 无法识别你的公钥。这里有几个步骤可以帮助你解决这个问题:

  1. 检查 SSH 密钥

首先,确保你已经在本地生成了 SSH 密钥,并且已经将其添加到 SSH agent 中。你可以通过以下命令来检查:

检查是否已生成 SSH 密钥

ls -al ~/.ssh

这应该会列出你的私钥和公钥文件,通常是 id_rsa 和 id_rsa.pub

启动 SSH agent

eval "$(ssh-agent -s)"

添加你的私钥到 SSH agent

ssh-add ~/.ssh/id_rsa

  1. 查看 SSH 配置

确保你的 ~/.ssh/config 文件(如果存在)或者全局 SSH 配置文件(通常位于 /etc/ssh/ssh_config)正确设置了 Host github.com 的参数。例如:

Host github.com

HostName github.com

User git

PreferredAuthentications publickey

IdentityFile ~/.ssh/id_rsa

  1. 检查公钥是否在 GitHub 上注册

登录到 GitHub,进入你的账户设置 -> SSH 和 GPG 密钥,检查你的公钥是否已经列在那里。如果没有,你需要添加它:

打开终端,查看你的公钥:

cat ~/.ssh/id_rsa.pub

复制输出的内容。

在 GitHub 的设置中,点击"New SSH key"或"Add SSH key",粘贴你的公钥,并保存。

  1. 测试 SSH 连接

在命令行中,尝试使用以下命令测试 SSH 连接:

ssh -T git@github.com

如果一切设置正确,你应该会看到类似 "Hi [username]! You've successfully authenticated, but GitHub does not provide shell access." 的消息。

  1. 使用 HTTPS 替代 SSH(如果问题持续存在)

如果问题依旧,你可以尝试使用 HTTPS URL 来克隆仓库,而不是 SSH URL:

git clone https://github.com/username/repository.git

然后使用你的 GitHub 用户名和密码进行认证。

  1. 检查防火墙和代理设置

如果你在公司或学校网络后面,可能存在网络代理或防火墙限制。确保你的网络设置允许你访问 GitHub。如果你使用代理,确保你的 Git 配置了正确的代理设置:

git config --global http.proxy 'http://proxy.example.com:8080'

git config --global https.proxy 'https://proxy.example.com:8080'

然后再次尝试连接。如果你不再需要通过代理,可以使用:

git config --global --unset http.proxy

git config --global --unset https.proxy

按照这些步骤操作后,通常可以解决大部分关于 SSH 密钥的问题。如果问题仍然存在,可能需要更详细地检查你的系统设置或联系网络管理员。