Git报错Permission denied (publickey)怎么办?SSH密钥怎么配置?

文章导读
遇到 Git 报错 Permission denied (publickey),核心原因是 SSH 密钥链断裂,平台无法识别本地身份。这不是仓库不存在,而是认证环节出了问题。
📋 目录
  1. 1. 确认远程仓库协议
  2. 2. 生成 SSH 密钥
  3. 3. 配置公钥到代码平台
  4. 4. 启动 SSH 代理 (含 Windows 专属)
  5. 5. 修复权限与多密钥配置
  6. 6. 验证连接是否生效
  7. 常见坑与排查
A A

遇到 Git 报错 Permission denied (publickey),核心原因是 SSH 密钥链断裂,平台无法识别本地身份。这不是仓库不存在,而是认证环节出了问题。

先说结论:本地私钥未加载或公钥未配置到平台,导致 SSH 握手失败。

  • 先确认:运行 git remote -v 确认远程地址是 SSH 协议(git@开头)
  • 先处理:生成 ed25519 密钥,公钥粘贴到平台,启动 ssh-agent 加载私钥
  • 再验证:运行 ssh -T git@github.com 看到成功认证提示才算过关

1. 确认远程仓库协议

SSH 密钥仅对 SSH 协议的仓库地址生效。如果当前使用的是 HTTPS 地址,配置 SSH 密钥无效。

检查命令:

git remote -v

结果判断:

  • SSH 协议:显示 git@github.com:username/repo.git(需配置 SSH)
  • HTTPS 协议:显示 https://github.com/username/repo.git(需配置 Credential 或切换协议)

若需切换为 SSH 协议,执行:

Git报错Permission denied (publickey)怎么办?SSH密钥怎么配置?
git remote set-url origin git@github.com:username/repo.git

2. 生成 SSH 密钥

推荐使用 ed25519 算法,安全性更高且兼容性好。生成时请替换为你的邮箱。

ssh-keygen -t ed25519 -C "your_email@example.com"

连续回车使用默认路径(~/.ssh/id_ed25519)。生成后确认文件存在:

ls -al ~/.ssh/id_ed25519*

3. 配置公钥到代码平台

将公钥内容复制到 GitHub/Gitee/GitLab 的 SSH Keys 设置页。

# Mac/Linux 查看公钥
cat ~/.ssh/id_ed25519.pub

# Windows PowerShell 查看公钥
type $env:USERPROFILE\.ssh\id_ed25519.pub

复制全部内容(包含 ssh-ed25519 开头到邮箱结尾),粘贴到平台设置页并保存。

4. 启动 SSH 代理 (含 Windows 专属)

私钥必须加载到 ssh-agent 才能被 Git 调用。不同系统处理方式不同:

Git报错Permission denied (publickey)怎么办?SSH密钥怎么配置?

Mac/Linux 用户:

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

Windows 用户:

Windows 10/11 自带 OpenSSH 服务,建议启用系统服务而非仅依赖 Git Bash 临时代理。

# PowerShell 管理员模式运行
# 1. 检查服务状态
Get-Service ssh-agent

# 2. 启动服务
Start-Service ssh-agent

# 3. 设置开机自启(可选)
Set-Service ssh-agent -StartupType Automatic

# 4. 添加密钥
ssh-add $env:USERPROFILE\.ssh\id_ed25519

5. 修复权限与多密钥配置

权限修复:私钥权限过宽会导致拒绝连接,Linux/Mac 下执行:

Git报错Permission denied (publickey)怎么办?SSH密钥怎么配置?
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519

多密钥配置(SSH Config):若你有多个密钥(如个人与公司分开),需创建配置文件指定对应关系。

创建或编辑 ~/.ssh/config 文件:

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes

Host gitlab.company.com
  HostName gitlab.company.com
  User git
  IdentityFile ~/.ssh/id_rsa_company

配置后 Git 会自动匹配对应密钥,无需手动 ssh-add。

6. 验证连接是否生效

执行测试命令,注意不同平台域名不同:

# GitHub
ssh -T git@github.com

# Gitee
ssh -T git@gitee.com

# GitLab
ssh -T git@gitlab.com

成功标志:看到 Hi username! You've successfully authenticated 类似提示。

常见坑与排查

  • 命令语法错误:配置 Git 全局代理时不要多加反引号,正确写法:git config `--global` url."https://github.com/".insteadOf "ssh://git@github.com/"(仅作为无法使用 SSH 时的备选方案)。
  • 密钥算法禁用:OpenSSH 8.8+ 默认禁用 rsa-sha1,若必须使用 RSA 密钥,需在 config 中添加 PubkeyAcceptedAlgorithms +ssh-rsa
  • 分支保护拦截:若 push 被拒提示 pre-receive hook declined,通常是分支保护策略,与 SSH 无关,不要盲目重配密钥。
  • 多个密钥冲突:若 ssh-add 加载了多个密钥,SSH 可能尝试错误的密钥。在 config 中设置 IdentitiesOnly yes 强制指定密钥。