Git之同一台電腦連接多個遠程倉庫


問題描述

有時候我們需要在同一台電腦上連接多個遠程倉庫,比如連接兩個GitHub賬號,那么需要兩個條件。
1.生成兩對 私鑰/公鑰,並且密鑰文件命名不能重復。
2.push 到remote時區分兩個賬戶,推送到相應的倉庫。

相應配置

1.在MAC的終端中輸入以下命令,查看密鑰。

ls ~/.ssh

如果有 id_rsaid_rsa.pub,說明已存在一對密鑰/公鑰。

2.創建新的 密鑰/公鑰,並指定密鑰名稱,比如id_rsa_x(x為任意名稱)

ssh-keygen -t rsa -f ~/.ssh/id_rsa_x -C "yourmail@xxx.com" 

操作完成后,該目錄會多出 id_rsa_xid_rsa_x.pub 兩個文件。

3.在 ~/.ssh/ 文件夾下創建一個 config 文件

$ touch config
$ vim config

編輯config文件,配置不同的倉庫指向不同的密鑰文件。

# 第一個賬號,默認使用的賬號 Host github.com HostName github.com User git IdentityFile ~/.ssh/id_rsa # 第二個賬號 Host second.github.com # second為前綴名,可以任意設置 HostName github.com #//這里填你們公司的git網址即可
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_x

原理分析
1.ssh 客戶端是通過類似 git@github.com:githubUserName/repName.git ** 的地址來識別使用本地的哪個私鑰的,地址中的 User 是@前面的git, Host 是@后面的github.com
2.如果所有賬號的 User 和 Host 都為 git 和 github.com,那么就只能使用一個私鑰。所以要對User 和 Host 進行配置,讓每個賬號使用自己的 Host,每個 Host 的域名做 CNAME 解析到 github.com,如上面配置中的Host second.github.com
3.配置了別名之后,新的地址就是
git@second.github.com:githubUserName/repName.git**(在添加遠程倉庫時使用)。
這樣 ssh 在連接時就可以區別不同的賬號了。

4.查看SSH 密鑰的值,分別添加到對應的 GitHub 賬戶中

$ cat id_rsa.pub
$ cat id_rsa_x.pub

把這兩個值分別 copy 到 GitHub 賬號中的 SSH keys 中保存。

5.清空本地的 SSH 緩存,添加新的 SSH 密鑰 到 SSH agent中

$ ssh-add -D
$ ssh-add id_rsa
$ ssh-add id_rsa_x

執行ssh-add時出現Could not open a connection to your authentication agent

若執行ssh-add /path/to/xxx.pem是出現這個錯誤:Could not open a connection to your authentication agent,則先執行如下命令即可:

  ssh-agent bash

最后確認一下新密鑰已經添加成功

$ ssh-add -l

6.測試 ssh 鏈接

ssh -T git@github.com
ssh -T git@second.github.com
# xxx! You’ve successfully authenticated, but GitHub does not provide bash access. # 出現上述提示,連接成功 

7.取消 git 全局用戶名/郵箱的設置,設置獨立的 用戶名/郵箱

# 取消全局 用戶名/郵箱 配置 $ git config --global --unset user.name $ git config --global --unset user.email # 進入項目文件夾,單獨設置每個repo 用戶名/郵箱 $ git config user.email "xxxx@xx.com" $ git config user.name "xxxx" 

查看git項目的配置

git config --list

8.命令行進入項目目錄,重建 origin (whatever 為相應項目地址)

$ git remote rm origin
# 遠程倉庫地址,注意Host名稱 $ git remote add origin git@second.github.com:githubUserName/repName.git $ git remote -v # 查看遠程 

10.遠程 push 測試
首先在 GitHub 上新建一個名為 testProj 的遠程倉庫,然后再在本地建一個本地倉庫。

$ cd ~/documnts $ mkdir testProj 

1.進入 testProj 文件夾,創建 REDME.md文件
2.初始化此文件夾為git
3.添加並提交README.md到Git本地倉庫
4.添加遠程倉庫
5.把README.md推送到遠程倉庫

$ cd testProj $ echo "# ludilala.github.io" >> README.md $ git init $ git add README.md $ git commit -m "first commit" # 如果前面已添加遠程連接,就無需再次添加 $ git remote add origin https://github.com/ludilalaa/ludilala.github.io.git $ git push -u origin master


參考:https://www.jianshu.com/p/f7f4142a1556





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM