Git:Permission Denied(密钥问题)


平台:GitHub、Gitee、GitLab 等。

1、问题描述

  • 问题:使用 Git 远程连接(clone/push)时报错 Permission denied

    Permission denied(publickey).
    fatal: Could not read from remote repository.
    
    Please make sure you have the correce access rights and the repository exitsrs.
    
  • 原因:排除仓库地址不存在的情况,说明 Git 平台上没有本地的 SSH KEY(密钥)

2、解决

2.1、检查本机密钥

  1. 进入 Git Bash:右键或开始菜单

    image-20220512144658396

  2. 查看密钥信息:在 ~/.ssh 文件夹下

    • 若文件夹不存在,则 mkdir手动创建。

      mkdir ~/.ssh
      
    • 若已存在 id_rsaid_rsa.pub,则无需生成新密钥。

      image-20220512144855937

2.2、生成密钥 *

若不存在 id_rsaid_rsa.pub,则需生成密钥

  1. 配置全局的 nameemail(与 Git 平台账号相同)

    git config --global user.name "用户名"
    git config --global user.email "邮箱"
    
  2. 生成 Key:生成过程中会提示输入信息,直接回车即可。

    ssh -keygen -t rsa -C "邮箱"
    
  3. 本地 C:\Users\用户名\.ssh 生成 id_rsaid_rsa.pub 文件。

    image-20220512145829273

2.3、配置密钥

以 GitLab 为例

  1. 在 GitLab 平台添加密钥(从 id_rsa.pub 全选复制)

    image-20220512150055666

  2. 检查密钥:在 Git Bash 中输入

    ssh -T git@Git平台地址
    # 示例
    ssh -T git@github.com
    ssh -T git@bitbucket.org
    
  3. 不同 Git 平台的成功提示信息有所区别,提示成功即可(welcome/successful)

Git