有时会使用多个git在线服务,比如有github,华为云,码云,coding
我们需要为不同的git生成相应的公私钥
1. 打开Git Bash,查看自己所有的SSH-Key
$ cd ~/.ssh
$ ls
id_rsa
id_rsa.pub
known_hosts
如果你已经创建过git账号那你可能会看到有一个SSH-Key
2. 生成github账号的SSH-Key
$ ssh-keygen -t rsa -C "github账号邮箱"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): github_id_rsa
第一个内容输入github_id_rsa(区分其他git服务的名字),然后一路回车即可
3. 生成其他SSH-Key,比如华为云git服务
和生成github一样,执行
$ ssh-keygen -t rsa -C "华为云账号邮箱"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): huaweicloud_id_rsa
起一个独有的名字huaweicloud_id_rsa用于区分其他,然后一路回车
4. 添加config配置文件用于区分多个SSH-Key
在电脑中.ssh文件下新建config文件,内容如下
# 华为云
Host codehub.devcloud.huaweicloud.com
HostName codehub.devcloud.huaweicloud.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/huaweicloud_id_rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa
5. 在github或者华为云里添加相应的SSH密钥
title(标题)随便填写,key(密钥)就是.ssh文件下对应的XXX_id_rsa.pub文件里的内容,复制粘贴即可
6. 测试一下
$ ssh -T git@github.com
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
$ ssh -T git@codehub.devcloud.huaweicloud.com
Welcome to Devcloud, username!
7. 配置同一个服务下的两个账号
比如再配置另一个华为云账号的SSH-key,新名字huaweicloud2_id_rsa
$ ssh-keygen -t rsa -C "华为云另一个账号邮箱"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): huaweicloud2_id_rsa
config文件中添加huaweicloud2后,如下
# 华为云(账号1)
Host codehub.devcloud.huaweicloud.com
HostName codehub.devcloud.huaweicloud.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/huaweicloud_id_rsa
# 华为云(账号2)
Host huaweicloud2
HostName codehub.devcloud.huaweicloud.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/huaweicloud2_id_rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa
在华为云账号2中添加SSH密钥后,测试
$ ssh -T git@huaweicloud2
Welcome to Devcloud, username!
注意:使用SSH地址时,需要根据config文件中的Host名替换部分内容,否则找不到仓库
比如华为云(账号2):
SSH原始地址:git@codehub.devcloud.huaweicloud.com:1ea72e48d91a4f329bc3a2119dd590f7/tess.git
在本地clone时需要用:git@huaweicloud2:1ea72e48d91a4f329bc3a2119dd590f7/tess.git