Linux ·

如何在同一台电脑上使用两个GitHub账户

场景:使用github的时候,大家都知道需要给该账号添加一个SSH key才能访问,参考 具体设置 。当然如果你在多台机器使用一个账户,你可以为该账户添加多个SSH key。由于github是使用SSH key的fingerprint来判定你是哪个账户,而不是通过用户名,这样你就可以在设置完之后,在本地直接执行下面的语句,它就会自动使用你的.ssh/id_rsa.pub所对应的账户进行登陆,然后执行相关命令。

1 #本地建库
2 $ git init
3 $ git commit -am "first commit'
4 
5 #push到github上去
6 $ git remote add origin [email protected]:xxxx/test.git
7 $ git push origin master

但是如果你想在一台机器使用两个github账号(比如私人账号和工作用账号)。这个时候怎么指定push到哪个账号的test仓库上去呢? 

解决方案(假设你已经拥有私有账号且已经OK,现在想使用另一个工作用账号):

1:为工作账号生成SSH Key

$ ssh-keygen -t rsa -C "your-email-address"

#存储key的时候,不要覆盖现有的id_rsa,使用一个新的名字,比如id_rsa_work 

2:把id_rsa_work.pub加到你的work账号上 

3:把该key加到ssh agent上。由于不是使用默认的.ssh/id_rsa,所以你需要显示告诉ssh agent你的新key的位置

$ ssh-add ~/.ssh/id_rsa_work

# 可以通过ssh-add -l来确认结果 

4:配置.ssh/config

$ vi .ssh/config

# 加上以下内容
#default github
Host github.com
  HostName github.com
  IdentityFile ~/.ssh/id_rsa

Host github_work
  HostName github.com
  IdentityFile ~/.ssh/id_rsa_work 

5:这样的话,你就可以通过使用github.com别名github_work来明确说你要是使用id_rsa_work的SSH key来连接github,即使用工作账号进行操作。

#本地建库
$ git init
$ git commit -am "first commit'
 
#push到github上去
$ git remote add origin git@github_work:xxxx/test.git
$ git push origin master

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 

参与评论