windows git:添加SSH key

git若是使用https協議,每次push時都會提示輸入用戶名和密碼,使用ssh祕鑰(git協議)則能夠避免這一麻煩。git

配置方法:
一、進入目錄~/.sshgithub

$ cd ~/.ssh
1
在windows下,這個目錄通常爲C:\Users\your_username.sshshell

二、建立ssh keywindows

$ ssh-keygen -t rsa -C "your_email@example.com"
1
代碼參數含義:bash

-t 指定密鑰類型,默認是rsa,能夠省略。
-C 設置註釋文字,好比郵箱。
-f 指定密鑰文件存儲文件名。dom

以上代碼省略了 -f 參數,所以,運行上面那條命令後會讓你輸入一個文件名,用於保存剛纔生成的ssh key代碼,如:ssh

Generating public/private rsa key pair.
# Enter file in which to save the key (/c/Users/you/.ssh/id_rsa): [Press enter]
1
2
若不輸入直接按enter,則使用默認文件名(強烈建議這麼作!!!!),並在~/.ssh目錄下生成id_rsa和id_rsa.pub兩個文件編輯器

而後會提示輸入密碼ide

Enter passphrase (empty for no passphrase): 
# Enter same passphrase again:
1
2
這個密碼是每次push時須要輸入的密碼。一樣地,也能夠不輸入密碼,直接按回車跳過這個步驟,這樣之後push的時候才能不用輸密碼工具

以後就會顯示以下

Your identification has been saved in /c/Users/saltyfish/.ssh/id_rsa.
Your public key has been saved in /c/Users/saltyfish/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:BRxQ5G4VITTmcxEO9da8AL8MIg9Aw/2bRgQiR3D4Xto qxy65535@gmail.com
The key's randomart image is:
+---[RSA 2048]----+
|    .o. oO&+*=   |
|     .o..O+* + o |
|       .o.B.+..oo|
|        .=.= oo o|
|        So*.+. o.|
|         =+o.Eo .|
|        .  .   o |
|                 |
|                 |
+----[SHA256]-----+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
三、添加ssh key到github
到key生成目錄~/.ssh下找到id_rsa.pub文件並用編輯器打開,複製裏面的內容;
在github->setting->SSH and GPG keys的SSH keys選擇New SSH key,將從id_rsa.pub中複製到的內容粘貼進去並點擊Add SSH key

這樣就OK了

四、測試ssh key
在git bash中輸入

$ ssh -T git@github.com
1
獲得如下回應就算成功

$ ssh -T git@github.com
Hi qxy65535! You've successfully authenticated, but GitHub does not provide shell access.
1
2
五、使用ssh進行push
在git bash輸入remote -v查看當前的remote url

$ git remote -v
1
若獲得的鏈接是以https開頭的,例如

origin  https://github.com/qxy65535/tfjs_test.git (fetch)
origin  https://github.com/qxy65535/tfjs_test.git (push)
1
2
說明此時是以https協議訪問該倉庫,若配完ssh key不想每次輸密碼,須要將它替換成git協議:

$ git remote set-url origin git@github.com:qxy65535/tfjs_test.git
1
之後再用git push就不須要密碼了

遇到的問題
一、使用ssh -T出現Permission denied (publickey).
緣由:SSH密鑰對不匹配。這個錯誤主要密匙全路徑名不相符,結果致使本地的SSH工具沒法找到到正確的密匙。
解決:首先檢查步驟2中生成的兩個文件是否確實在~/.ssh路徑下,如過不是,把它們移過去。
其次是很是重要的一點,若是你在步驟2中自定義了ssh key的文件名,那麼緣由就在於你的命名與ssh內設定的名字不一致,所以須要手動添加祕鑰。不少教程大概不是windows系統。。直接讓輸入命令

$ ssh-add ~/.ssh/你的文件名
1
因而就有了問題2

二、執行ssh-add時出現Could not open a connection to your authentication agent
其實應該將自定義名字的祕鑰交給ssh-agent管理:GitHub help:Generating a new SSH key and adding it to the ssh-agent

# start the ssh-agent in the background
$ eval $(ssh-agent -s)
Agent pid 59566
$ ssh-add ~/.ssh/id_rsa
1
2
3
4
可是這樣很麻煩,難道每次重啓git bash都要打這麼一套前奏嗎??
固然不會,因此能夠把這段代碼加入到git bash的啓動腳本中去。
使用編輯器打開Git安裝目錄下的etc/bash.bashrc文件,在末尾添加兩行

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/你的文件名
1
2
保存退出便可。

用ssh-add除了能更改ssh祕鑰的文件名,也徹底能夠用來更改祕鑰的路徑,好比ssh-add your_path/your_key

遇到的問題都是起源於給ssh key文件自定義了一個文件名。。因此沒什麼特殊要求的話,仍是一路enter使用默認吧_(:3」∠)_ ---------------------  做者:sssaltyfish  來源:CSDN  原文:https://blog.csdn.net/weixin_43344725/article/details/83388291  版權聲明:本文爲博主原創文章,轉載請附上博文連接!

相關文章
相關標籤/搜索