同一台电脑上使用多个github账号在多个仓库中开发

应用场景:我有一个私人的github账号平时用于个人开发和学习,而公司开发有一个单独的github账号用于开发公司项目。这两个账号我都需要同时在同一台PC上用到。

主要步骤:

生成公钥

为了方便在生成后直接看到公钥,可以直接打开 .ssh所在目录(c:/Users/pcname/.ssh/),这里的pcname是你对应windows用户名,具体因PC而异。

  • 生成第一把公钥
ssh-keygen -t rsa -b 4096 -C "[email protected]"
# 设置公钥名称【id_rsa_office】,默认为id_rsa
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa_office
# 设置公钥密码-
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa_office.
Your public key has been saved in id_rsa_office.pub.
  • 完成以上设置后,就生成了第一个公钥,可以直接在./ssh文件夹下看到id_rsa_office[私钥]和id_rsa_office.pub[公钥]
  • 以相同的方式可以生成第二个账号的公钥。
ssh-keygen -t rsa -b 4096 -C "[email protected]"
Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa_private

添加公钥

  • 在github对应的管理控制台中添加公钥
  • 打开:Setting/SSH and GPG keys
  • New SSH keys
    在这里插入图片描述

配置公钥

在.ssh文件夹下,通过touch config命令生成config文件,然后编写config配置

##可缺省,此时ssh -T [email protected],默认就是和拥有id_rsa.pub的github账号对接。
   #github server one
   Host office              
   Hostname github.com      
   User git                     
   IdentityFile ~/.ssh/id_rsa_office  
   
   #github server two
   Host private
   Hostname github.com
   User git
   IdentityFile ~/.ssh/id_rsa_private
  • 说明:
    1. Host 可以是自定的随意别名,如office,在后面clone时会用到
    2. Hostname 就默认配置就好【默认使用的github.com
    3. User 默认都使用git就好
    4. IdentityFile 即公钥对应目录

测试

ssh -T office
Hi office! You've successfully authenticated, but GitHub does not provide shel l access.

提示 Hi xxx表示配置成功

克隆开发

  • 对于office帐号下的仓库:
git clone office:githubname/repository.git

(原地址是:[email protected]:githubname/repository.git,替换后应该是:office:githubname/repository.git)

  • 对于private帐号下的仓库:
git clone private:githubname/repository.git

(原地址是:[email protected]:githubname/repository.git,替换后应该是:private:githubname/repository.git)

最后

1、一把公钥只能被一个GITHUB帐号拥有->因此必须为不同的帐号创建公钥。

2、交互时需要本地私钥与GITHUB帐号的公钥配对。

因此,要在同一台电脑上给两个属于不同帐号的仓库提交时,必须在本地创建两对公/私钥匙,分别把两把公钥给两个帐号,提交时根据要提交的仓库所属帐号选择相应的本地私钥即可;

当我们要在一个仓库上PUSH提交的内容时,使用以上的步骤可以选择对应的公钥,GITHUB服务器收到提交的内容时,先解析出仓库地址,然后从该仓库的所属帐号中找到一把能解锁该提交的公钥。

发布了114 篇原创文章 · 获赞 146 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/Sophie_U/article/details/85259549