DEBUG.WIKI
RackNerd;$21.99/年 · 1GB KVM
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →
腾讯云;让你的想法跑起来;轻量服务器 · 建站 / Docker / API;查看产品 →

解决 Git 报错 Permission denied (publickey) SSH 密钥认证失败

执行 git clone 或 git push 时提示 Permission denied (publickey). fatal: Could not read from remote repository。本文详解 SSH 密钥生成算法变更(OpenSSH 8.8+ 废弃 SHA-1)、~/.ssh/config 主机映射及权限配比排障流程。

问题现象

尝试从 GitHub、GitLab 或自建 Gerrit 仓库拉取/推送代码时,操作被阻断:

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.

触发根因

  1. 未在客户端配置对应公钥:本地未生成 SSH Key 或未将 id_rsa.pub 内容复制添加到远端平台账号的 SSH Keys 设置中。
  2. OpenSSH 8.8+ 废弃 RSA-SHA1 签名算法:现代操作系统(如 Ubuntu 22.04+、macOS Ventura+)默认禁用了不安全的 ssh-rsa(SHA-1 算法),如果使用的是旧版 RSA 密钥,远端或本地客户端会直接拒绝握手。
  3. ~/.ssh 目录与文件权限过大:SSH 客户端具有严格安全校验,若私钥文件或 .ssh 目录权限过宽(如 777 或同组可读),SSH 客户端会静默忽略该私钥。
  4. 多账号密钥冲突:本地存在多个 Git 账号(如公司 GitLab 与个人 GitHub),SSH 客户端默认使用第一把密钥导致认证被拒。

诊断排查步骤

使用详细调试模式连接目标 Git 服务器测试握手过程:

ssh -vT git@github.com

观察输出末尾的认证日志:

  • 若提示 debug1: send_pubkey_test: no mutual signature algorithm,表明遇到了 OpenSSH 8.8+ 废弃老旧 RSA 算法的问题。
  • 若提示 debug1: Trying private key: /home/user/.ssh/id_rsa 接着全量 Permission denied,表明公钥未在平台上配置或私钥文件未被加载。

解决方案

方案一:生成现代 Ed25519 椭圆曲线密钥(强烈推荐)

推荐弃用旧版 1024/2048 位 RSA 密钥,换用性能更好且更安全的 Ed25519:

# 1. 生成现代 Ed25519 密钥
ssh-keygen -t ed25519 -C "your_email@example.com"

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

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

将打印出的文本完整粘贴到 GitHub/GitLab 的 Settings -> SSH Keys 中。

方案二:修正 SSH 目录与私钥权限

确保本地权限符合严格权限策略:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_*
chmod 644 ~/.ssh/*.pub
chmod 600 ~/.ssh/config 2>/dev/null || true

方案三:配置 ~/.ssh/config 解决多密钥与兼容性问题

编辑 ~/.ssh/config,针对特定主机指定专用私钥路径:

# GitHub 个人配置
Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

# 如果必须继续使用旧版 RSA 密钥与老旧 GitLab 兼容:
Host gitlab.old-company.com
    HostName gitlab.old-company.com
    User git
    IdentityFile ~/.ssh/id_rsa
    PubkeyAcceptedKeyTypes +ssh-rsa

验证方法

运行独立连通性验证:

ssh -T git@github.com

GitHub 正常回显:

Hi username! You've successfully authenticated, but GitHub does not provide shell access.

之后再执行 git clone 或 git pull 即可顺畅完成。