同时使用:gitlab & github

生成密钥

gitlab 密钥

ssh-keygen -t rsa -C "gitlab 用户邮箱地址" ←┘
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/user/.ssh/id_rsa): ←┘
Enter passphrase (empty for no passphrase): ←┘
Enter same passphrase again: ←┘
...

github 密钥

ssh-keygen -t rsa -C "github 用户邮箱地址" ←┘
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/user/.ssh/id_rsa): id_rsa_github ←┘
Enter passphrase (empty for no passphrase): ←┘
Enter same passphrase again: ←┘
...

~/.ssh/ 目录下生成以下文件:

 - id_rsa
 - id_rsa.pub 
 - id_rsa_github
 - id_rsa_github.pub

分别将 id_rsa.pub 和 id_rsa_github.pub 内容复制到 gitlab 或 github 的 ssh key 中

添加 config 文件

# gitlab
Host gitlab
    HostName gitlab.com
    IdentityFile ~/.ssh/id_rsa

# github
Host github
    HostName github.com
    IdentityFile ~/.ssh/id_rsa_github

测试连接

gitlab

ssh -T git@gitlab.com ←┘
The authenticity of host 'gitlab.com (52.167.219.168)' can't be established.
ECDSA key fingerprint is SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw.
Are you sure you want to continue connecting (yes/no)? yes ←┘
...
Welcome to GitLab, username!

github

ssh -T git@github.com ←┘
The authenticity of host 'github.com (52.167.219.168)' can't be established.
ECDSA key fingerprint is SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw.
Are you sure you want to continue connecting (yes/no)? yes ←┘
...
Hi username! You've successfully authenticated, but GitHub does not provide shell access.

会在 ~/.ssh/ 目录下自动生成 known_hosts 文件

测试连接失败,Permission denied (publickey).

原因是,我们自定义了 id_rsa_github 钥匙名,默认情况下,连接会搜索 id_rsa 钥匙名,所以这里会失败
可以通过 ssh -T -v git@github.com 了解连接失败的具体原因

ssh-agent

# 开启 agent
eval $(ssh-agent -s) ←┘
Agent pid 8428
# 添加 钥匙名
ssh-add ~/.ssh/id_rsa_github ←┘
Identity added: /c/Users/user/.ssh/id_rsa_github (/c/Users/user/.ssh/id_rsa_github)
# 查看 agent list
ssh-add -l ←┘
8428 SHA256:A9UcJMadwTpF7TvsT5LEXsSssTs5qehmV9Q2Q8Ntw3o /c/Users/user/.ssh/id_rsa_github (RSA)
# 不用时可以关闭 agent
eval $(ssh-agent -k) ←┘
Agent pid 8428 killed

注意:使用github时,记得在自己的项目下定义 local user.name 和 local user.email

git config --local user.name ''
git config --local user.email ''
    原文作者:china_zoushuang
    原文地址: https://segmentfault.com/a/1190000011810785
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞