Skip to content

报错 git@github.com: Permission denied (publickey) 解决

用 SSH 方式操作时报:

text
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

意思是 SSH 公钥认证失败——GitHub 不认你这台机器的密钥。逐步排查。

第 1 步:确认有没有 SSH key

bash
ls -al ~/.ssh
# 看有没有 id_ed25519 / id_rsa 及对应 .pub 文件

没有就生成:

bash
ssh-keygen -t ed25519 -C "your_email@example.com"
# 一路回车用默认路径即可

第 2 步:把公钥添加到 GitHub

bash
# 复制公钥内容
cat ~/.ssh/id_ed25519.pub

Windows PowerShell:

powershell
Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub

到 GitHub → Settings → SSH and GPG keys → New SSH key,粘贴保存。

⚠️ 添加的是 .pub 公钥,千万别贴私钥。

第 3 步:测试连接

bash
ssh -T git@github.com
# 成功:Hi username! You've successfully authenticated...

第 4 步:key 没被 ssh-agent 加载

有时 key 存在但没被使用,尤其自定义了文件名时:

bash
# 启动 agent 并添加 key
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

第 5 步:用 -v 看详细过程

还不行就看 SSH 到底用了哪个 key:

bash
ssh -vT git@github.com
# 观察 "Offering public key" 有没有用到你添加的那个

常见变体报错

no matching host key type found / unable to negotiate 新旧算法不匹配,或走了 443。在 ~/.ssh/config 指定:

text
Host github.com
  Hostname ssh.github.com
  Port 443
  User git
  IdentityFile ~/.ssh/id_ed25519

(顺带解决 22 端口被封,见 SSH 443。)

用错了远程地址 确认是 SSH 地址而非 HTTPS:

bash
git remote -v
# 应为 git@github.com:用户/仓库.git;若是 https 则是另一套认证(见下)

如果你其实想用 HTTPS + token,那是另一回事,见 密码认证被移除

速查

情况解决
没有 key第 1 步生成
有 key 没加到 GitHub第 2 步添加公钥
key 没被使用第 4 步 ssh-add
no matching host key~/.ssh/config 指定 + 443
其实想用 HTTPS改用 PAT

小结

  • 三板斧:生成 key → 加公钥到 GitHub → ssh -T 测试
  • 自定义 key 名要 ssh-add 或在 config 里 IdentityFile 指定。
  • 加的是公钥(.pub),别泄露私钥。

本文仅供技术学习与研究,请遵守所在国家/地区法律法规。

本站为技术学习交流站点,与 GitHub, Inc. 无任何隶属或官方关系。所有内容仅供技术研究与学习,请遵守所在国家/地区的法律法规。