LoginSignup
0
0

プライベートリポジトリからGit for Windowsを使用してgit cloneができない

Last updated at Posted at 2023-08-28

問題

PowerShellでssh -T git@github.comが成功するのに,gitコマンドからsshを叩くと失敗する.

具体的には...

GitHubとsshでの通信を行うのに必要な最低限の操作を行った.

  • ssh-keygenによりC:\Users\{User}\.ssh以下に鍵を作成.
  • 公開鍵をGitHubに登録
  • .ssh以下にconfigファイルを作成
  • $HOME環境変数にC:\Users\{User}を設定することでssh -T git@github.comが成功することを確認.

その後,sshでのgit clonegit pushなど,gitコマンドからsshを叩くようなコマンドを打ったとき,以下のようなエラーが発生する.

PS C:\Users\{user}\projects> git clone git@github.com:*****/{private_repository}.git
Cloning into '{private_repository}'...
The authenticity of host 'github.com (20.27.177.113)' can't be established.
ED25519 key fingerprint is SHA256:+*************.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
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).
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.

よく見ると,$HOME環境変数を設定しているのに,/home/{user}/.sshのようにLinuxのようなパス指定が行われている.
そのため,gitがホームディレクトリを認識できておらず,ホームディレクトリ以下の.sshディレクトリも見れていない.このためknown_hostsや鍵が発見できずcloneに失敗する.

解決策

git bashを使用する

git bashでwhere ssh,PowerShellでgcm sshをそれぞれ実行することにより,sshコマンドで実行するファイルのパスがわかる.
筆者の場合,以下であった.

  • git bash: C:\Program Files\Git\usr\bin\ssh.exe
  • PowerShell: C:\Windows\System32\OpenSSH\ssh.exe

git bashはデフォルトでOpenSSHではなくgitのsshを使用しているようである.インストール時に設定で変えられるかもしれないが未調査.
このため,この段階でgit bashでssh -T git@github.comを叩いても失敗した.

を参考にC:\Users\{User}以下に.bash_profileファイルを作成し,PATH="/c/Windows/System32/OpenSSH:${PATH}"の記述を加えて環境変数を変更し,sshコマンドで先にOpenSSHが読み込まれるようにした.

これにより,git bashでssh -T git@github.comが成功することを確認.また,sshを用いたgit clonegit pushもできるようになった.

gitconfigを変更する

C:\Users\{User}\.gitconfig,もしくはC:\Program Files\Git\etc\gitconfig(システムレベルのconfigをいじりたくないなら非推奨)に,以下の記述を追加

[core]
	sshCommand = C:/Windows/System32/OpenSSH/ssh.exe

これでgitのsshではなくOpenSSHを使うようになり,sshを用いたgit clonegit pushもできるようになる.

参考

環境

  • Windows10
  • PowerShell
    • version 5.1.19041.3031
  • git for windows
    • git version 2.41.0.windows.3
  • ssh
    • OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0