SSH 無法建立 .ssh 目錄錯誤處理

問題描述

在使用 Git 或 SSH 連線時出現以下錯誤訊息:

Could not create directory '/home/User/.ssh' (No such file or directory).
Failed to add the host to the list of known hosts (/home/User/.ssh/known_hosts).

此錯誤通常出現在 Windows 系統中,原因是 Git 使用內建的 SSH 或其他非原生工具時,預設路徑指向 Unix 系統的 /home/User/.ssh,但該路徑在 Windows 中並不存在,導致無法建立 .ssh 目錄與 known_hosts 檔案。


解決方式

方式一:設定 Git 使用正確的 SSH 檔案路徑

建立或修改 SSH 設定檔案(config)內容如下,請依實際路徑替換:

# C:\Users\YourUsername\.ssh\config
Host git-codecommit.*.amazonaws.com
    User YourUsername
    IdentityFile C:\Users\YourUsername\.ssh\id_rsa
    UserKnownHostsFile C:\Users\YourUsername\.ssh\known_hosts
    HostkeyAlgorithms +ssh-rsa
    PubkeyAcceptedKeyTypes +ssh-rsa

IdentityFileUserKnownHostsFile 的路徑應使用 Windows 全路徑格式(例如 C:/Users/User/.ssh/id_rsa),避免使用 Unix 格式。

方式二:透過 Git 指令強制指定 SSH 命令

使用以下指令將 SSH 設定寫入 Git 全域設定中:

git config --global core.sshCommand "ssh -i C:/Users/User/.ssh/id_rsa -o UserKnownHostsFile=C:/Users/User/.ssh/known_hosts"

參數說明:

  • core.sshCommand:指定 Git 使用哪個 SSH 指令。
  • -i:指定私鑰路徑。
  • -o UserKnownHostsFile=...:指定 known_hosts 檔案位置(可避免預設寫入 /home/User/...)。
  • 若不想檢查 host key,可使用 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null,但不建議在正式環境使用,有資安風險。

查詢與驗證設定

查詢目前 Git 的 SSH 設定

git config --global core.sshCommand

查看 .ssh 資料夾內容

Get-ChildItem -Force "$env:USERPROFILE\.ssh"

查看個別檔案內容

  • 檢查 config 設定檔:
Get-Content "$env:USERPROFILE\.ssh\config"
  • 檢查私鑰 id_rsa 內容:
Get-Content "$env:USERPROFILE\.ssh\id_rsa"
  • 檢查公鑰 id_rsa.pub 內容:
Get-Content "$env:USERPROFILE\.ssh\id_rsa.pub"
  • 檢查 known_hosts 檔案內容:
Get-Content "$env:USERPROFILE\.ssh\known_hosts"

移除設定

若要移除 Git 全域的 SSH 設定,可執行:

git config --global --unset core.sshCommand

附註

  • .ssh 資料夾預設應位於使用者目錄中:C:\Users\<你的帳號>\.ssh
  • .ssh 不存在,可以手動建立資料夾,並將金鑰與 config 檔放入
  • 記得將檔案權限設為安全的狀態(如必要,可將 id_rsa 設為唯讀)

如需進一步參考,可查看: