SourceTree权限错误和Mac配置多个id_rsa秘钥

778 阅读2分钟

进入ssh目录,查看目录

cd ~/.ssh                                                     
ls                                                            

ls命令效果

config            id_rsa.pub        id_rsa_github.pub known_hosts.old
id_rsa            id_rsa_github     known_hosts

生成非对称加密密钥,默认名称id_rsa

ssh-keygen -t rsa -C "youremail@yourcompany.com"

指定秘钥名称id_rsa_github,名字任意定

ssh-keygen -t rsa -C "youremail@yourcompany.com" -f ~/.ssh/id_rsa_github

配置config文件

vim config
# gitlab rsa pub
# Host相当于别名,随便取,使用的时候注意名称一致,git clone git@NBGit:Andy/Andy_Interview.git
# 此处Host别名会有大坑,请看文章最下面的【注意点】
Host NBGit 
    # HostName:域名
    HostName github.com
    # 账号,不配置User也可生效
    User Andy@outlook.com
    # 权限
    PreferredAuthentications publickey
    # 对应域名下的秘钥
    IdentityFile ~/.ssh/id_rsa_github

# gitlab rsa pub
Host gitlab
    HostName gitlab.com
    User Andy@gitlab.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa

测试

ssh -T git@NBGit
Hi Andy! You've successfully authenticated, but GitHub does not provide shell access.

用法示例, 我现在要拉取git@github.com:AppHock/UploadFile.git的代码 需要将git@github.com:AppHock替换成git@NBGit:AppHock

git clone git@NBGit:AppHock/UploadFile.git
ssh -T git@gitlab
Welcome to GitLab, @Andy!

注意点

SourceTree管理多个仓库,github、gitlab、自己公司的仓库域名等多个仓库。SourceTree拉取自己Github仓库的代码,修改之后push时失败,一直提示权限错误,但是Github已经配置了当前电脑的rsa公钥

该问题就是因为~/.ssh文件下有多个rsa秘钥,我当前config文件配置的github的Host为 NBGit,但是sourceTree不能自动识别NBGit这个别名,就会导致sourceTree向Github权限校验的时候用默认的id_rsa秘钥(我的gitlab秘钥)去验证,Github就会返回权限校验失败问题

所以再配置config文件时,还是要按照正常思路来配置

# Host保证和HostName一致,Host千万别用别名了,会导致SourceTree不能正常获取对应的rsa秘钥去鉴权
Host github.com 
    # HostName:域名
    HostName github.com
    # 账号,不配置User也可生效
    User Andy@outlook.com
    # 权限
    PreferredAuthentications publickey
    # 对应域名下的秘钥
    IdentityFile ~/.ssh/id_rsa_github

# gitlab rsa pub
Host gitlab.com
    HostName gitlab.com
    User Andy@gitlab.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa