多账号私钥混肴导致没有权限问题
github使用SSH与客户端连接。如果是单用户(first),生成密钥对后,将公钥保存至github,每次连接时SSH客户端发送本地私钥(默认~/.ssh/id_rsa)到服务端验证。单用户情况下,连接的服务器上保存的公钥和发送的私钥自然是配对的。但是如果是多用户(first,second),我们在连接到second的帐号时,second保存的是自己的公钥,但是SSH客户端依然发送默认私钥,即first的私钥,那么这个验证自然无法通过。不过,要实现多帐号下的SSH key切换在客户端做一些配置即可。
首先cd到~/.ssh 使用 ssh-keygen -t -rsa -C ‘xxxxx@mail.com’ 生成新的SSH key:id_rsa_second,生成完后将新的SSH public key添加到github/码云。
首先cd到账户根目录下的隐藏文件夹下 .ssh (前提设置为,windows隐藏目录可见):
1 | cd ~/.ssh |
生成第一个码云账号公钥并添加到码云ssh绑定页面
生成第一个码云账号的ssh 私钥
1 | ssh-keygen -t rsa -C '码云绑定的邮箱@163.com' -f ~/.ssh/gitee_177XXXXX_id_rsa |
查看第一个码云账号本地生成的公钥串
1 | cat ~/.ssh/gitee_177XXXXX_id_rsa.pub |
公钥添加到码云
生成第二个码云账号公钥并添加到码云ssh绑定页面
生成第二个码云账号的ssh 私钥
1 | ssh-keygen -t rsa -C '码云绑定邮箱@91bihu.com' -f ~/.ssh/gitee_chuanling_id_rsa |
查看第二个码云账号本地生成的公钥串
1 | cat ~/.ssh/gitee_chuanling_id_rsa.pub |
公钥添加到码云, 同上;
生成 github账号公钥并添加到github ssh绑定页面
生成github账号的ssh 私钥
1 | ssh-keygen -t rsa -C 'github绑定邮箱@github.com' -f ~/.ssh/github_46XXXX_id_rsa |
查看github账号本地生成的公钥串
1 | cat ~/.ssh/github_46XXXX_id_rsa.pub |
将查到的公钥添加到github,如下;
配置SSH agent
默认SSH只会读取id_rsa,所以为了让SSH识别新的私钥,需要将其添加到SSH agent
1 | ssh-add ~/.ssh/gitee_177XXXXX_id_rsa |
第二个码云账号和github账号,同样按照这个配置;
可能出现如下问题
该命令如果报错:Could not open a connection to your authentication agent.无法连接到ssh agent,可执行
1 | ssh-agent bash |
命令后再执行ssh-add命令。
完成以上步骤后在~/.ssh目录创建config文件,该文件用于配置私钥对应的服务器。内容如下:
1 | # gitee 177XXXXX@163.com account |
Host 命名可以随意即可,方便自己记忆,后续在添加remote是还需要用到。
主要修改下 IdentityFile 字段, 将对应的私钥配置正确即可;
测试是否配置成功:
1 | ssh -T git@github.com-xcl-net |
配置完成后,在连接非默认帐号的github仓库时,远程库的地址要对应地做一些修改,比如现在添加second帐号下的一个仓库test,则需要这样添加:
1 | git remote add test git@(上面配置的Host):second/test.git #并非原来的git@github.com:second/test.git |
这样,多个账号就可以同时使用ssh, 免输入账号密码拉去提交代码了;
后记
可能有如下问题, 我没遇到这个;
注意:github根据配置文件的user.email来获取github帐号显示author信息,所以对于多帐号用户一定要记得将user.email改为相应的email(second@mail.com)。
1 | 遗留问题,每次pull & push 都需要输入yes //已解决,如下 |
1 | ssh-keygen -R 116.211.167.14 |
参考: https://blog.csdn.net/u013378029/article/details/88309165