1. 前言
有时候我们会有多个 Git 账号, 如 GitHub,GitLab, 这时如果使用同一个邮件注册, 那不会有问题, 但是假如用的是不同的邮件注册账号, 这就需要生成不同的 SSH 文件并为其配置相应的域名.
2. 生成一个 SSH-Key
$ SSH-keygen -t rsa -C "youremail@email.com"// 自己 Git 账号对应的邮箱
假如一路 next 下去, 你会得到:
- id_rsa
- id_rsa.pub
这样不是不可以, 但是我们要生成多个, 所以最好起有区分的名字.
3. 设置密码
可以不设置, 也可以键入密码
4. 重复步骤 2 和 3, 生成对应的 rsa 和 rsa.pub 文件
- //GitHub 生成的对应 SSH-key
- id_github_ras // 私钥
- id_github_ras.pub // 公钥
- //GitLab 生成的对应 SSH-key
- id_gitlab_ras
- id_gitlab_ras.pub
5. 配置 SSH-key 到对应的域名
5.1 在~/.SSH 目录下生成一个 config 文件
- cd ~/.SSH
- VIM config
5.2 在 config 文件中键入
- Host GitHub
- HostName GitHub.com
- User Git
- PreferredAuthentications publickey
- # 下面填写的是私钥名, 没有 pub 后缀
- IdentityFile ~/.SSH/id_github_rsa
- Host GitLab
- HostName GitLab.com
- User Git
- PreferredAuthentications publickey
- IdentityFile ~/.SSH/id_gitlab_rsa
6. 将专有密钥添加到 SSH-agent 中
- SSH-add ~./SSH/id_github_rsa
- SSH-add ~./SSH/id_gitlab_rsa
tips:
把专有密钥添加到 SSH-agent 中
SSH-add ~./SSH/id_rsa
从 SSH-agent 中删除密钥
SSH-add -d ./SSH/id_rsa.pub
查看 SSH-agent 中的密钥
SSH-add -l
7. 将 rsa.pub 加入到 GitHub/GitLab 等网站
cat ~./SSH/id_github_rsa
将该字符串拷贝粘贴到 Git 网站对应添加 SSH-key 的地方:
- GitHub:
- Setting->SSH and GPG keys
- GitLab:
- Setting->SSH keys
其他网站自己找到添加 SSH-key 的位置, 添加即可.
8. 现在就可以使用 SSH 而不是 https 愉快的玩耍 Git 了
- Git clone Git@GitHub.com:XXX/demo.Git
- Git clone Git@GitLab.com:XXX/demo.Git
来源: https://juejin.im/post/5bf6092a6fb9a04a0279fb6a