1. 前言
以下說明在Windows環境中,使用Git for Windows、TortoiseGit、IDEA等Git客戶端時,使用SSH密鑰方式訪問Git服務器,不輸入密碼。
2. 環境準備
以下使用OpenSSH作爲SSH客戶端,所需使用的軟件下載地址如下。
OpenSSH下載地址:https://www.mls-software.com/opensshd.html
Git for Windows下載地址:https://git-scm.com/download/win
TortoiseGit下載地址:https://tortoisegit.org/download/
IDEA下載地址:https://www.jetbrains.com/idea/download/#section=windows
3. 生成SSH密鑰對
OpenSSH建議安裝7.5p1-1或更高的版本。
OpenSSH安裝完畢後,會自動添加至環境變量Path中,不需要手工添加。
使用OpenSSH的ssh-keygen命令生成SSH密鑰對。
打開Windows命令行窗口,在任意目錄,執行以下命令:
ssh-keygen -t rsa -b 4096 |
提示“Enter passphrase”“ Enter same passphrase again”時,直接回車。
提示信息如下所示:
C:\Users\user>ssh-keygen -t rsa -b 4096 Generating public/private rsa key pair. Enter file in which to save the key (/home/user/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user/.ssh/id_rsa. Your public key has been saved in /home/ user /.ssh/id_rsa.pub. The key fingerprint is: SHA256:... user@MACHINE The key's randomart image is: +---[RSA 4096]----+ |+o .. . ... | | .. o +.. | |. ... . | | ..*.. * ... | | +.o.= .= | | * . =.*.+ o | |= o o= . | |o. . =.. | |. .+ | +----[SHA256]-----+ |
當執行完畢後,會在當前用戶目錄的.ssh目錄生成文件,如Windows 7中爲“C:\Users\[用戶名]\.ssh”,可執行“cd %USERPROFILE%\.ssh”進入。
生成的文件包括id_rsa、id_rsa.pub,分別爲私鑰與公鑰文件。
4. 在Git服務器配置SSH公鑰
以Github爲例,打開settings菜單,“SSH and GPG keys”頁面,點擊“New SSH key”按鈕,出現如下界面:
Title可輸入任意值。
Key輸入上一步生成的id_rsa.pub公鑰文件內容,內容以“ssh-rsa”開頭。
完成添加後,在Git客戶端可以正常執行pull/push等操作,不需要輸入密碼。
5. Git客戶端設置
5.1 TortoiseGit
TortoiseGitPlink是TortoiseGit默認的SSH客戶端,在進行pull/push等操作時,需要啓動pageant.exe程序,並選擇使用的密鑰,不是特別方便。
可將TortoiseGit默認的SSH客戶端修改爲OpenSSH,會使用上述配置的SSH密鑰,在進行pull/push等操作時,不需要啓動pageant.exe程序,也不需要選擇使用的密鑰,如下所示:
在“運行”或控制檯窗口中執行“ tortoisegitproc /command:firststart ”命令,打開TortoiseGit配置窗口,點擊下一步到“Authentication and credential store”窗口,選擇SSH客戶端爲OpenSSH,如下圖所示。
完成以上修改後,可打開TortoiseGit的Settings窗口檢查是否生效,打開Network菜單,SSH client應爲ssh.exe。也可直接將SSH client修改爲ssh.exe。
5.2 Git for Windows
Git for Windows安裝完畢後,若沒有添加至環境變量Path中,需要手工添加。
上述步驟執行完畢後,Git for Windows不需要進行配置,即可正常執行pull/push等操作。
5.3 IDEA
上述步驟執行完畢後,IDEA不需要進行配置,即可正常執行pull/push等操作。
可使用項目的Git菜單的pull/push等功能,或在Terminal中執行Git命令,如下所示: