Git提交時有Https和SSH兩種驗證方式冈涧,Https方式除了速度慢以外清女,在每次提交時還需要輸入帳號和密碼独榴;而使用SSH可以生成一個公鑰-私鑰對块饺,我們會把公鑰添加到Git的服務(wù)器,把私鑰放在本地朴沿。提交文件的時候Git服務(wù)器會用公鑰和客戶端提交私鑰做驗證猜谚,如果驗證通過則提交成功败砂。
對于Github添加公鑰有以下幾種情況:
1.單個Github用戶推送單個Github用戶;
2.單個Github用戶推送多個Github用戶魏铅;
3.多個Github用戶推送多個Github用戶昌犹;
對于單個Github用戶推送單個Github用戶
1 首先需要設(shè)置git全局用戶信息
git config --global user.name "yourName"
git config --global user.email "yourEmail"
2 查看SSH版本,若沒有輸出览芳,則需要安裝SSH
ssh -V
sudo apt-get install openssh-client openssh-server #SSH安裝命令
3 生成新的SSH key
cd ~/.ssh
#若沒有id_rsa和id_rsa.pub 則可以使用默認生成命令
ssh-keygen -t rsa -C "some explanations"
#若之前已存在斜姥,可以自定義生成
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_new
在~/.ssh目錄下有id_rsa/id_rsa_new(私鑰)和 id_rsa.pub/id_rsa_new.pub(公鑰)兩個文件,其中.pub文件里存放的即是公鑰key沧竟。
4 添加私鑰
ssh-add ~/.ssh/id_rsa
5 添加公鑰
登錄到GitHub铸敏,選擇settings ,選擇Add SSH key悟泵,把.pub的內(nèi)容復(fù)制到里面即可杈笔。
6 測試
ssh -T git@github.com
Hi xxx You've successfully authenticated, but GitHub does not provide shell access.
如果有以上提示,說明公鑰添加成功糕非。
單個Github用戶推送多個Github用戶
這種情況多用于同一個用戶推送不同項目的倉庫(如個人項目和工作項目):
1 生成多個SSH key
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_p
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_w
2 添加私鑰
ssh-add ~/.ssh/id_rsa_p
ssh-add ~/.ssh/id_rsa_w
3 修改配置文件
vim config
#personal
Host personal
HostName github.com
User uesrname@example.com
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_p
#work
Host work
HostName github.com
User username@example.com
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_w
4 添加不同公鑰到對應(yīng)GitHub賬戶
5 測試
ssh -T git@personal #git@Host
Hi xxx You've successfully authenticated, but GitHub does not provide shell access
如果有以上提示蒙具,說明連接成功。
對于多個Github用戶推送多個Github用戶
這種情況多用于不同用戶推送不同Github用戶的倉庫(個人賬戶到個人項目倉庫峰弹,工作賬戶推送工作項目倉庫)店量,和配置單個Git用戶的方式不同,這里我們需要為每個項目分別配置鞠呈,所以要命令行進入倉庫文件夾再設(shè)置融师。
1 生成多個SSH key
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_p2p
ssh-keygen -t rsa -C "some explanations” -f ~/.ssh/id_rsa_w2w
2 添加私鑰
ssh-add ~/.ssh/id_rsa_p2p
ssh-add ~/.ssh/id_rsa_w2w
3 修改配置文件
cd ~/.ssh
vim config
#personal to personal
Host p2p
HostName github.com
User personalAccount@example.com
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_p2p
#work to work
Host w2w
HostName github.com
User workAccount@example.com
PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_w2w
4 添加不同公鑰到對應(yīng)GitHub賬戶
5 添加局部用戶信息
cd personalRepository
git config --local user.name "yourName"
git config --local user.email "personalAccount@example.com"
cd workRepository
git config --local user.name "yourName"
git config --local user.email "workAccount@example.com"
其中全局用戶信息存在~/.gitconfig中,局部用戶信息存在對應(yīng)倉庫目錄.git/config中蚁吝。