Git是分布式的代碼管理工具,它的代碼管理是基于SSH
和HTTPS
的。
在clone項目時,我們通常使用HTTPS url
或SSH url
克隆到本地。
這兩種方式的主要區別在于:
使用
HTTPS url
克隆對初學者來說會比較方便,復制HTTPS url
到git Bash里然后用clone命令克隆到本地就好了,但是每次fetch
和push
代碼時,都需要輸入賬號和密碼,這也是HTTPS
方式的麻煩之處。
使用
SSH url
克隆卻需要在克隆之前先配置和添加好SSH key
。因此,如果你想要使用SSH url
克隆的話,你必須是這個項目的擁有者。否則你是無法添加SSH key
,另外SSH
默認是每次fetch
和push
代碼都不需要輸入賬號和密碼,所謂先苦后甜嘛。
下面有一個錯誤的例子:
如果是git倉庫的擁有者,使用SSH url
克隆后,未添加SSH就直接把本地代碼同步到遠程倉庫,會報以下錯誤:
$ git push origin master
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
以上錯誤的原因是SSH key不存在或者SSH key未被添加到Github上,因此權限被拒絕了。
接下我們開始為Git配置SSH key:
1.判斷SSH key是否存在:
cd ~/.ssh
如果沒有密鑰則不會進入此文件夾。
2.生成SSH key:
$ ssh-keygen -t rsa -C "email地址"
// 按3次回車,密碼為空。(你也可以設置密碼)
Your identification has been saved in /home/tekkub/.ssh/id_rsa.
Your public key has been saved in /home/tekkub/.ssh/id_rsa.pub.
The key fingerprint is:
默認會在.ssh文件夾下生成兩個名為 id_rsa
和 id_rsa.pub
的文件:
一般路徑是:C:\Users\Administrator\.ssh
最后在github上添加SSH key,這里要添加的是 id_rsa.pub
里的公鑰。
1.png
SSH key