1.前言
有时候我们会有多个git账号,如GitHub,GitLab,这时如果使用同一个邮件注册,那不会有问题,但是假如用的是不同的邮件注册账号,这就需要生成不同的ssh文件并为其配置相应的域名。
2.生成一个SSH-Key
$ ssh-keygen -t rsa -C "youremail@email.com"//自己git账号对应的邮箱
如若一路enter,你会得到:
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.pub
将该字符串拷贝粘贴到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