目录

gitlab-add-an-ssh-key-多个ssh配置

gitlab add an ssh key 多个ssh配置

前言

当你的git需要访问不放环境的时候,你看需要配置多个ssh配置

配置多个 Git 账号可以通过在 ~/.ssh 目录下创建不同的 SSH 密钥文件和配置文件来实现。

生成不同的ssh秘钥

创建SSH Key。在用户主目录下,看看有没有.ssh目录,如果有,再看看这个目录下有没有id_rsa和id_rsa.pub这两个文件,如果已经有了,可直接跳到下一步。如果没有,Git Bash,创建SSH Key

在命令行中(Open Git Bash here)执行以下命令来生成不同的 SSH 密钥(可以不设置密码,不让每次访问都要输入密码):

ssh-keygen -t rsa -C "your_email@example.com" -f ~/.ssh/id_rsa_first_account

ssh-keygen -t rsa -C "your_email@example.com" -f ~/.ssh/id_rsa_second_account

其中,id_rsa_first_account 和 id_rsa_second_account 分别是第一个和第二个账号的密钥文件名称。

https://i-blog.csdnimg.cn/direct/93646e3a560f464caccc6fed85b8b7fa.png

在 GitLab 或者 GitHub 上添加公钥

https://i-blog.csdnimg.cn/direct/e1871d6b3ca6499a80ffc239c5303bc8.png

在 ~/.ssh 目录下创建 config 文件

# First account
Host gitlab.com-first-account  最好也是网址 不然git命令用不能用
  HostName gitlab.com 网址
  User git
  IdentityFile ~/.ssh/id_rsa_first_account

# Second account
Host gitlab.com-second-account 最好也是网址 不然git命令用不能用
  HostName gitlab.com 网址
  User git
  IdentityFile ~/.ssh/id_rsa_second_account

其中,Host 字段需要根据自己的 GitLab 或者 GitHub 地址进行修改。IdentityFile 字段需要指向之前生成的不同密钥文件的路径。

Host的名字可以取为自己喜欢的名字,不过这个会影响git相关命令,例如:Host mygithub 这样定义的话,命令如下,即git@后面紧跟的名字改为mygithub,例如:git clone git@mygithub:xxx/****.git

HostName要是git的网址

Clone 代码仓库

在克隆代码仓库时,通过指定不同的 Host 来使用不同的账号进行克隆。例如:

git clone :username/project.git

或者

git clone :username/project.git

这样就可以使用不同的账号克隆不同的代码仓库了。

总结

代码能够正常下载下来,则配置完成