Git创建多个ssh key

时间:2023-03-09 18:49:50
Git创建多个ssh key

在使用git的时候,遇到需要创建多个ssh key的需求,一个用来git hub项目,一个用来git lab项目;

之前如果已将创建过一个ssh key,那么在创建第二个的时候,要修改默认名称,然后增加配置文件;

之前创建ssh key生成了如下两个文件,一个私钥,一个公钥
id_rsa
id_rsa.pub

我们要生成新的一个ssh key,由于路径跟之前的一直,所以要改个名字
id_rsa_gitlab
id_rsa_gitlab.pub

具体如下

ssh-keygen -t rsa -f ~/.ssh/id_rsa_gitlab -C "a@b.com"

注意:因为SSH默认只读取id_rsa,为了让SSH识别新的私钥,需要使用命令将其添加到SSH agent,命令如下:
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_gitlab

若执行ssh-add时提示“Could not open a connection to your authentication agent”,则执行下面的命令:
ssh-agent bash
然后再运行ssh-add命令(可以通过ssh-add -l查看私钥列表);

接着修改配置文件:
在~./ssh目录下新建一个config文件,命令如下:
touch config

配置文件如下:
#github
Host github.com
IdentityFile ~/.ssh/id_rsa
User a@b.com

#gitlab
Host gitlab.com
IdentityFile ~/.ssh/id_rsa_gitlab
User a@b.com