1. 前提條件
安裝 Git。
2. 創建公鑰
打開.ssh
文件夾(位於:C:\Users\Administrator\.ssh),右鍵文件夾空白處,打開 Git Bash
(Git 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,碼雲……)的倉庫時,當進行clone
或push
操作時,極有可能出現如下情況:(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
的公鑰對於 clone
或 push
的倉庫的可訪問性,當出現多個公鑰時,我們就需要告訴 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
成功。
簡要原理
當我們 clone
、push
不同賬戶或不同平臺倉庫時,我們希望能控制在不同的地方使用不同的公鑰。
注意到倉庫提供的克隆 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
類似於變量名,該變量下由HostName
和User
來定義標識信息,IdentityFile
則聲明瞭公鑰的位置,因此我們可以使用如下命令來克隆倉庫:
$git clone pubKey1:XXX/xxx.git
歸納:push和clone
指定公鑰後,相應的push
和clone
操作如下:
$git clone pubKey1:XXX/xxx.git # clone
# 添加並查看遠程倉庫
$git remote add gitee pubKey1:XXX/xxx.git
$git remote -v
gitee pubKey1:XXX/xxx.git (fetch)
gitee pubKey1:XXX/xxx.git (push)
# push
$git push gitee master