**问题描述:**
在使用 Git 通过 SSH 协议克隆仓库时,开发者常遇到“Permission denied (publickey)”错误。这通常是因为未正确生成 SSH 密钥对,或未将公钥添加到 Git 账户。用户可能不清楚如何在本地生成 SSH 密钥、如何检查密钥是否已添加到 SSH 代理,或如何将公钥配置到 GitHub、GitLab 等平台。此外,多账户配置时密钥路径未指定或配置错误也常导致认证失败。掌握 SSH 密钥的生成、添加与验证流程,是解决此类问题的关键步骤。
1条回答 默认 最新
fafa阿花 2025-08-21 14:20关注1. 问题现象:Permission denied (publickey)
在使用 Git 通过 SSH 协议克隆仓库时,开发者常遇到“Permission denied (publickey)”错误。这种错误通常表现为:
git clone git@github.com:username/repo.git Cloning into 'repo'... Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.该错误的核心原因在于 SSH 认证失败,常见于密钥未正确生成、未添加到 SSH 代理或未配置到 Git 平台。
2. 常见原因分析
- 未生成 SSH 密钥对
- 生成的密钥未添加到 SSH 代理
- 公钥未正确添加至 GitHub、GitLab 等平台的账户设置中
- 多账户环境下,未指定正确的密钥路径
- SSH 配置文件(~/.ssh/config)配置错误
3. 解决流程概览(Mermaid 流程图)
graph TD A[开始] --> B[检查是否存在 SSH 密钥] B --> C{密钥是否存在?} C -->|是| D[检查是否添加到 SSH Agent] C -->|否| E[生成新的 SSH 密钥] D --> F{是否已添加?} F -->|否| G[添加密钥到 SSH Agent] G --> H[将公钥添加到 Git 平台账户] H --> I[测试 SSH 连接] I --> J{连接成功?} J -->|是| K[完成] J -->|否| L[检查 SSH 配置和权限]4. 分步操作指南
- 生成 SSH 密钥对:
或使用 RSA(兼容旧系统):ssh-keygen -t ed25519 -C "your_email@example.com"ssh-keygen -t rsa -b 4096 -C "your_email@example.com" - 查看生成的密钥:
输出示例:ls -al ~/.ssh文件名 说明 id_ed25519 私钥文件 id_ed25519.pub 公钥文件 - 启动 SSH Agent:
eval "$(ssh-agent -s)" - 添加私钥到 SSH Agent:
ssh-add ~/.ssh/id_ed25519 - 复制公钥内容:
将输出内容复制到剪贴板。cat ~/.ssh/id_ed25519.pub - 将公钥添加到 Git 平台:
登录 GitHub、GitLab 等平台,进入账户设置中的 SSH Keys 页面,粘贴公钥内容。 - 测试 SSH 连接:
成功输出示例:ssh -T git@github.comHi username! You've successfully authenticated, but GitHub does not provide shell access.
5. 多账户配置与 SSH Config 文件
当需要配置多个 Git 账户时,需在
~/.ssh/config文件中添加配置,例如:# GitHub - Personal Host github.com HostName github.com User git IdentityFile ~/.ssh/id_ed25519_personal # GitHub - Work Host github-work HostName github.com User git IdentityFile ~/.ssh/id_ed25519_work使用时修改远程仓库的 SSH 地址:
git remote set-url origin git@github-work:username/repo.git本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报