多个github帐号的SSH key切换

来源:互联网 发布:vue.js window.open 编辑:程序博客网 时间:2024/05/16 23:38
1. 首先cd到~/.ssh 使用 ssh-keygen -t -rsa -C ‘second@mail.com’ 生成新的SSH key:id_rsa_second

ssh-keygen -t rsa -C 'second@mail.com'

2. 默认SSH只会读取id_rsa,所以为了让SSH识别新的私钥,需要将其添加到SSH agent 
ssh-add ~/.ssh/id_rsa_second 
该命令如果报错:Could not open a connection to your authentication agent.无法连接到ssh agent,可执行ssh-agent bash命令后再执行ssh-add命令。

3. 完成以上步骤后在~/.ssh目录创建config文件,该文件用于配置私钥对应的服务器。内容如下

# Default github user(first@mail.com)
Host github.com
HostName ssh.github.com
Port 443
User git
IdentityFile /home/username/.ssh/id_rsa

# second user(second@mail.com)
Host github-second
HostName ssh.github.com
Port 443
User git
IdentityFile /home/.ssh/id_rsa_second

4. 配置完成后,在连接非默认帐号的github仓库时,远程库的地址要对应地做一些修改,比如现在添加second帐号下的一个仓库test,则需要这样添加:
git remote add test git@github-second:second/test.git #并非原来的git@github.com:second/test.git

这样每次连接都会使用id_rsa_second与服务器进行连接。至此,大功告成!

注意: github根据配置文件的user.email来获取github帐号显示author信息,所以对于多帐号用户一定要记得将user.email改为相应的email(second@mail.com)

参考: 
http://omiga.org/blog/archives/2269 
https://help.github.com/articles/set-up-git 
http://www.rritw.com/my/api/apache_jinbuguo/OpenSSH/ssh-keygen.html 
http://rogerdudler.github.com/git-guide/index.zh.html 
https://help.github.com/articles/using-ssh-over-the-https-port


0 0