使用git,如果同时使用多个git托管网站,如gitlab和github,ssh key不一致,该如何切换呢?只有一个key时到没有问题,生成的默认key是~/.ssh/id_rsa,在windows os目录是C:\Users\Administrator\.ssh,直接用就是了。解决方案是配置~/.ssh/config文件。实验如下:
生成第一个key
$ ssh-keygen -t rsa -C "your_email@youremail.com"
最后在~/.ssh下生成2个文件,一个是公钥,一个是私钥
生成第二个key(假如邮箱是mail@xxx.com)::
$ ssh-keygen -t rsa -C "mail@xxx.com"
这时注意要给第二个key起个名字:
需要将新密钥添加到SSH agent中:
因为默认只读取id_rsa,为了让SSH识别新的私钥,需将其添加到SSH agent中:
ssh-add ~/.ssh/other
如果出现Could not open a connection to your authentication agent的错误,就试着用以下命令:
ssh-agent bash
ssh-add ~/.ssh/other
如果使用的是windows os,可以在C:\Users\Administrator目录下找到other和other.pub文件,将它们放到~/.ssh目录下。
配置config文件如下:
Host gitlab.gitlab.com
HostName gitlab.com
port 22
User git
IdentityFile ~/.ssh/id_rsa
Host other.github.com
HostName github.com
port 22
User git
IdentityFile ~/.ssh/other
执行以下命令:
提示You've successfully authenticated 就说明连接成功了
使用
clone,将Host换成config文件里的对应Host:
$git clone git@other.github.com:username/repo.git
修改remote:
$ git remote rm origin
$ git remote add origin@other.github.com:username/repo.git