我们在实际生产过程可能会遇到需要在一台电脑上配置不同 SSH Key 的情况。例如我们可能需要同时使用 GitHub 以及 GitLab 的情况,这时我们就需要配置不同的 SSH Key 了

Modern

使用 1Passwrod 管理 SSH Key

创建 SSH Key

  1. 点击创建项目(选择 SSH Key)
  2. 生成 New SSH Key(推荐使用 Ed25519)

image.png

添加 SSH Key

  1. 在 GitHub/Gitlab 中选择 SSH Key
  2. 使用 1Password 自动填充公钥

image.png

配置 Config 文件

增加 config 配置文件(若有则直接编辑,无则创建。路径 ~/.ssh/config

  1. # 创建 config 配置文件
  2. $ touch ~/.ssh/config

添加以下内容:

  1. Host *
  2. IdentityAgent "~/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock"

测试

  1. # 测试 SSH 连接
  2. $ ssh -T git@github.com
  3. $ ssh -T git@gitlab.example_company.com

image.png

只需要一份 SSH Key,可在不同的客户端使用

Legacy

创建 SSH Key

.pub 后缀的文件就是公钥,另一个文件则是私钥。

  1. # 生成 GitHub SSH Key
  2. $ ssh-keygen -t ed25519 -C 'your_email@example.com' -f ~/.ssh/github_rsa
  3. # 生成 GitLab SSH Key
  4. $ ssh-keygen -t ed25519 -C 'your_email@example.com' -f ~/.ssh/gitlab_rsa

若不想在使用公钥的时候输入密码,可以留空(直接回车即可)。

  1. # 添加私钥
  2. $ ssh-add ~/.ssh/github_rsa
  3. $ ssh-add ~/.ssh/gitlab_rsa
  4. # 额外两个命令
  5. # 列出私钥列表
  6. $ ssh-add -l
  7. # 删除所有私钥
  8. $ ssh-add -D

配置 Config 文件

增加 config 配置文件(若有则直接编辑,无则创建。路径 ~/.ssh/config

  1. # 创建 config 配置文件
  2. $ touch ~/.ssh/config

添加以下内容:

  1. # GitHub
  2. Host github
  3. Hostname github.com
  4. PreferredAuthentications publickey
  5. IdentityFile ~/.ssh/github_rsa
  6. # GitLab
  7. Host gitlab
  8. Hostname gitlab.com
  9. PreferredAuthentications publickey
  10. IdentityFile ~/.ssh/gitlab_rsa

注意:

  • Host 名称可以随便设置
  • HostName 则是网站的地址(例如:公司 GitLab 的地址是 gitlab.example_company.com,则 HostName 为该地址)

添加 SSH Key

  1. # 复制 SSH public key
  2. $ pbcopy < ~/.ssh/github_rsa.pub
  3. $ pbcopy < ~/.ssh/gitlab_rsa.pub

打开 GitHub - SSH and GPG keys 添加 SSH key 即可

  1. # 测试 SSH 连接
  2. $ ssh -T git@github.com
  3. $ ssh -T git@gitlab.example_company.com

References

  1. Connecting to GitHub with SSH
  2. 1Password for SSH & Git