2024年2月9日

Windows Conda 環境下使用 ssh 將 git repository 推送到 github 的方法(錯誤排除)

背景:透過Conda建立一個專門負責 git 任務的虛擬環境,並透過SSH途徑 push/pull Github 上面的 git repository,相關的公鑰與私鑰均已建立並部署完成。

錯誤訊息1 @ 推送權限不足產生錯誤:

(gitonly) PS E:\scripts\python\scripts> git push 

git@github.com: Permission denied (publickey).

fatal: Could not read from remote repository.

Please make sure you have the correct access rights

and the repository exists.

錯誤訊息2 @ 增加私鑰時的錯誤:

(gitonly) PS E:\scripts\python\scripts> ssh-add C:\Users\user\.ssh\for_github

Could not open a connection to your authentication agent.

經檢查發現
ssh-add 為 conda 所建立 git 環境下附帶的 ssh-add。

(gitonly) PS C:\Users\user> Get-Command ssh-add


CommandType     Name                                               Version    Source

-----------     ----                                               -------    ------

Application     ssh-add.exe                                        0.0.0.0    D:\ProgramData\miniconda3\envs\gitonly...


同時經檢查發現 ssh 為 conda 所建立 git 環境下附帶的 ssh。

(gitonly) PS C:\Users\user> Get-Command ssh


CommandType     Name                                               Version    Source

-----------     ----                                               -------    ------

Application     ssh.exe                                            0.0.0.0    D:\ProgramData\miniconda3\envs\gitonly...

解決方法:運用 Windows 本身附帶的 Windows

1. 先使用系統管理員權限開啟 Powershell 並啟動 SSH 服務
Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Start-Service ssh-agent
Get-Service ssh-agent | select -property Status,Name,DisplayName,Starttype

 Status Name      DisplayName                  StartType
 ------ ----      -----------                  ---------
Running ssh-agent OpenSSH Authentication Agent    Manual

2. 運用 Windows 系統自帶的 ssh-add 匯入私鑰
C:\Windows\System32\OpenSSH\ssh-add.exe C:\Users\user\.ssh\for_github
Identity added: C:\Users\user\.ssh\for_github (user@email.com)
3.  調整 git repository 預設的 SSH client 為 Windows 系統自帶的(要先切換到專案目錄下)
git config --local core.sshCommand "'C:/Windows/System32/OpenSSH/ssh.exe'"
4. 可以 git push 了。