外观
报错 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.pubWindows 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),别泄露私钥。
本文仅供技术学习与研究,请遵守所在国家/地区法律法规。