Linux ·

多个GitHub帐号的SSH key切换

一台电脑上有一个ssh key,在github上提交代码,由于其他原因,你可能会在一台电脑上提交到不同的github上,怎么办呢...

假设你电脑上一个ssh key都没有,如果有默认的一个了,请直接生成第二个

一、生成并添加第一个ssh key

$ ssh-keygen -t rsa -C "[email protected]"在Git Bash中执行命令一路回车,会在~/.ssh/目录下生成id_rsa和id_rsa.pub两个文件

用文本编辑器打开id_rsa.pub里的内容,在Github中添加SSH Keys

不明白的请参考GitHub创建SSH Keys

二、生成并添加第二个ssh key

$ ssh-keygen -t rsa -C "[email protected]"这次不要一路回车了,给这个文件起一个名字 不然默认的话就覆盖了之前生成的第一个

多个GitHub帐号的SSH key切换 Linux 第1张

假如起名叫my,目录结构如下:

多个GitHub帐号的SSH key切换 Linux 第2张

如果生成的第二个ssh key不在.ssh/下,可移动到此目录

三、在.ssh/下创建config文件 内容如下:
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Host my.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/my
Host名字随意,接下来会用到。

四、测试配置是否正确

多个GitHub帐号的SSH key切换 Linux 第3张

多个GitHub帐号的SSH key切换 Linux 第4张

如果出现Hi xxx!You've successfully authenticated 就说明连接成功了

现在就以下种情况给出不同的做法:
1、本地已经创建或已经clone到本地:

如下两种解决方法:

打开.git/config文件

#更改[remote "origin"]项中的url中的
#my.github.com 对应上面配置的host
[remote "origin"]
url = [email protected]:itmyline/blog.git或者在Git Bash中提交的时候修改remote

$ git remote rm origin
$ git remote add origin [email protected]:itmyline/blog.git2、clone仓库时对应配置host对应的账户

#my.github.com对应一个账号
git clone [email protected]:username/repo.git作者:itmyhome

GitHub 教程系列文章: 

通过GitHub创建个人技术博客图文详解  http://www.linuxidc.com/Linux/2015-02/114121.htm

GitHub 使用教程图文详解  http://www.linuxidc.com/Linux/2014-09/106230.htm 

Git 标签管理详解 http://www.linuxidc.com/Linux/2014-09/106231.htm 

Git 分支管理详解 http://www.linuxidc.com/Linux/2014-09/106232.htm 

Git 远程仓库详解 http://www.linuxidc.com/Linux/2014-09/106233.htm 

Git 本地仓库(Repository)详解 http://www.linuxidc.com/Linux/2014-09/106234.htm 

Git 服务器搭建与客户端安装  http://www.linuxidc.com/Linux/2014-05/101830.htm 

Git 概述 http://www.linuxidc.com/Linux/2014-05/101829.htm 

分享实用的GitHub 使用教程 http://www.linuxidc.com/Linux/2014-04/100556.htm 

参与评论