当你有多个 git 账号时,如 GitHub、Gitee、公司的 Gitlab 等,配置多个 SSH 就很重要了,想一想提交代码的场景(切换 git 账号,并且经常忘记切换)。

一、创建目录

在 ~/.ssh/ 目录下创建几个文件夹:github、gitee、company,分别用于存放各平台的 SSH Key,其中 company 可以改为你所在的公司名或组织名。

二、生成多个 SSH Key

1、生成 SSH Key

打开 Git Bash,为 GitHub 生成 SSH Key,这里指定了生成目录(请修改 email):

  1. ssh-keygen -t ed25519 -C "email@github" -f ~/.ssh/github/id_ed25519

这时,根据提示按两次回车(不设置密码,容易忘记)即可,生成的 SSH Key 在 ~/.ssh/github 目录下:id_ed25519 和 id_ed25519.pub。

2、复制公钥:

  1. # for Windows
  2. clip < ~/.ssh/github/id_ed25519.pub
  3. # for MacOX
  4. pbcopy < ~/.ssh/github/id_ed25519.pub

3、添加 SSH Key

打开 GitHub 官网并登录,在设置中添加 SSH Key,并填写 Title。

说明:
Title 可以取电脑具体型号、办公/个人等,就是说你得能通过 Title 判断这个 SSH Key 是哪台电脑的,这个很重要,以后办公电脑归还、离职后都用得上,不再使用的电脑,应及时删除对应的 SSH Key。

注意:
此时,还不能测试 SSH Key,因为生成的时候指定了路径,测试前必须配置路径。

4、重复1-3

为 Gitee 和 Your Company 生成 SSH Key:

  1. # for Gitee
  2. ssh-keygen -t ed25519 -C "email@gitee" -f ~/.ssh/gitee/id_ed25519
  3. # for your company
  4. ssh-keygen -t ed25519 -C "email@company" -f ~/.ssh/company/id_ed25519

复制公钥,并添加到对应平台上。

三、本地配置

1、创建 config 文件

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

2、配置 GitHub

在 config 文件中,做如下配置:

  1. # GitHub
  2. Host github.com
  3. HostName github.com
  4. PreferredAuthentications publickey
  5. IdentityFile ~/.ssh/github/id_ed25519

3、测试 SSH KEY

  1. ssh -T git@github.com

看到 successfully 意味着测试通过。

4、重复2-3

配置:

  1. # Gitee
  2. Host gitee.com
  3. HostName gitee.com
  4. PreferredAuthentications publickey
  5. IdentityFile ~/.ssh/gitee/id_ed25519
  6. # Your Company
  7. Host gitlab.com
  8. HostName 120.120.120.120
  9. PreferredAuthentications publickey,password
  10. IdentityFile ~/.ssh/company/id_ed25519

说明:

  1. Port:我们公司的 gitlab ,没有配置域名,通过 https://IP:8888/repo/path 访问,网上说此处需要配置 Port,我这加了 Port 反而失败。
  2. User:配置了好像没什么用,每个资源还是得指定 name 和 email,要么就是全局配置,这就失去了本文配置多个 SSH Key 的意义。

测试:

  1. # for Gitee
  2. ssh -T git@gitee.com
  3. # for your company
  4. ssh -T git@gitlab.com

补充

如果之前设置过全局用户名和邮箱,这里需要取消:

  1. git config --global --unset user.name
  2. git config --global --unset user.email

取消过后,将需要为每个 repo 单独设置用户名和邮箱。在提交代码时,IDE 会自动检测,如果没有设置,IDE 会提醒你设置,一般会默认勾选“设置为全局”,这个勾选得取消。

参考