1. 程式人生 > >Git 學習筆記(1)管理一臺電腦上的多個公鑰

Git 學習筆記(1)管理一臺電腦上的多個公鑰

1. 前提條件

 安裝 Git。

2. 建立公鑰

 開啟.ssh資料夾(位於:C:\Users\Administrator\.ssh),右鍵資料夾空白處,開啟 Git BashGit Bash here

 建立命令:

$ssh-keygen -t rsa -C "[email protected]" # 郵箱名自定

 設定儲存公鑰的檔名:(可以直接回車跳過,預設檔名為id_rsa

Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/325-43/.ssh/id_rsa)
: id_rsa_rswork

 之後設定密碼啥的直接跳過就可以了(如果不是特別必要的話)。

3. 新增公鑰到遠端倉庫

 公鑰的所有內容(一大串以我們設定的郵箱結尾的字串)都存放在.pub檔案中,新增到對應的遠端倉庫就可以啦。

4. 管理多個公鑰

 此時有兩個公鑰: 在這裡插入圖片描述  一個公鑰只能給一個遠端倉庫賬戶使用,當我們使用多個賬戶或者使用不同平臺(GitHub,GitLab,碼雲……)的倉庫時,當進行clonepush操作時,極有可能出現如下情況:(Access Denied,說明這是私有專案,直接clone,不出現問題才不正常呢。。。)

$git clone [email protected]
:XXX/xxx.git Cloning into 'xxx'... Access denied: Access Denied fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.

 在預設情況下,Git 會檢驗.ssh檔案中 id_rsa.pub 的公鑰對於 clonepush 的倉庫的可訪問性,當出現多個公鑰時,我們就需要告訴 Git 如何使用正確的公鑰來訪問專案。

 比如現在,我所訪問的這個專案是一個私有專案

,而我已經將 id_rsa_rswork.pub 中的公鑰新增到了該賬號下的ssh中了,然而直接clone依舊提示Access Denied,說明 Git 並沒有正確使用公鑰,我們開啟.ssh資料夾,在資料夾下建立檔案 config,在裡面寫入:

HOST pubKey1
HostName gitee.com
User git
IdentityFile ~/.ssh/id_rsa_rswork

 儲存,退出。其中,pubKey1是自定義的變數名,用於告訴 Git 應該使用哪個公鑰

 此時我們使用如下命令來克隆倉庫:

$git clone pubKey1:XXX/xxx.git

 成功。

簡要原理

 當我們 clonepush 不同賬戶或不同平臺倉庫時,我們希望能控制在不同的地方使用不同的公鑰

 注意到倉庫提供的克隆 ssh 為:(XXX是賬戶名,xxx是倉庫名,[email protected] 類似於標識資訊

[email protected]:XXX/xxx.git  # 碼雲
[email protected]:XXX/xxx.git # github

 當我們使用官方提供的標識資訊時,預設只讀取 .ssh 資料夾下 id_rsa.pub 中的公鑰。

config

HOST pubKey1
HostName gitee.com
User git
IdentityFile ~/.ssh/id_rsa_rswork

 配置檔案 config 的內容大致呈 1 + 3的結構, HOST 類似於變數名,該變數下由HostNameUser來定義標識資訊,IdentityFile 則聲明瞭公鑰的位置,因此我們可以使用如下命令來克隆倉庫:

$git clone pubKey1:XXX/xxx.git

end