当你有多个 git 账号时,如 GitHub、Gitee、公司的 Gitlab 等,配置多个 SSH 就很重要了,想一想提交代码的场景(切换 git 账号,并且经常忘记切换)。
一、创建目录
在 ~/.ssh/ 目录下创建几个文件夹:github、gitee、company,分别用于存放各平台的 SSH Key,其中 company 可以改为你所在的公司名或组织名。
二、生成多个 SSH Key
1、生成 SSH Key
打开 Git Bash,为 GitHub 生成 SSH Key,这里指定了生成目录(请修改 email):
ssh-keygen -t ed25519 -C "email@github" -f ~/.ssh/github/id_ed25519
这时,根据提示按两次回车(不设置密码,容易忘记)即可,生成的 SSH Key 在 ~/.ssh/github 目录下:id_ed25519 和 id_ed25519.pub。
2、复制公钥:
# for Windowsclip < ~/.ssh/github/id_ed25519.pub# for MacOXpbcopy < ~/.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:
# for Giteessh-keygen -t ed25519 -C "email@gitee" -f ~/.ssh/gitee/id_ed25519# for your companyssh-keygen -t ed25519 -C "email@company" -f ~/.ssh/company/id_ed25519
三、本地配置
1、创建 config 文件
2、配置 GitHub
在 config 文件中,做如下配置:
# GitHubHost github.comHostName github.comPreferredAuthentications publickeyIdentityFile ~/.ssh/github/id_ed25519
3、测试 SSH KEY
ssh -T git@github.com
4、重复2-3
配置:
# GiteeHost gitee.comHostName gitee.comPreferredAuthentications publickeyIdentityFile ~/.ssh/gitee/id_ed25519# Your CompanyHost gitlab.comHostName 120.120.120.120PreferredAuthentications publickey,passwordIdentityFile ~/.ssh/company/id_ed25519
说明:
- Port:我们公司的 gitlab ,没有配置域名,通过 https://IP:8888/repo/path 访问,网上说此处需要配置 Port,我这加了 Port 反而失败。
- User:配置了好像没什么用,每个资源还是得指定 name 和 email,要么就是全局配置,这就失去了本文配置多个 SSH Key 的意义。
测试:
# for Giteessh -T git@gitee.com# for your companyssh -T git@gitlab.com
补充
如果之前设置过全局用户名和邮箱,这里需要取消:
git config --global --unset user.namegit config --global --unset user.email
取消过后,将需要为每个 repo 单独设置用户名和邮箱。在提交代码时,IDE 会自动检测,如果没有设置,IDE 会提醒你设置,一般会默认勾选“设置为全局”,这个勾选得取消。
