2026/04/16(木)WindowsでSSH接続に使う秘密鍵を任意の場所に置く方法

投稿日:

C:\Users\hoge\.ssh以外の場所に秘密鍵を配置し、その秘密鍵を使ってWindows組み込みのSSHを利用して、SSH接続を行うと以下のようなエラーが出るので、それを回避する方法。

[00:11:24.734] Opening exec server for ssh-remote+hoge.example.com
[00:11:24.934] Initizing new exec server for ssh-remote+hoge.example.com
[00:11:24.934] Using commit id "xxxxx" and quality "stable" for server
[00:11:24.934] Extensions to install:
[00:11:24.939] Install and start server if needed
[00:11:24.963] Opening exec server for ssh-remote+hoge.example.com
[00:11:24.967] Running script with connection command: "C:\WINDOWS\System32\OpenSSH\ssh.exe" -T -D 65374 "hoge.example.com" sh
[00:11:24.968] Generated SSH command: 'type "C:\Users\hoge\AppData\Local\Temp\vscode-linux-multi-line-command-hoge.example.com-281649447.sh" | "C:\WINDOWS\System32\OpenSSH\ssh.exe" -T -D 65374 "hoge.example.com" sh'
[00:11:24.968] Using connect timeout of 17 seconds
[00:11:24.968] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[00:11:25.179] >
[00:11:25.179] Got some output, clearing connection timeout
[00:11:25.199] >
[00:11:26.323] >
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> @         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> Permissions for 'C:\\path\\to\\hoge.sec' are too open.
> It is required that your private key files are NOT accessible by others.
> This private key will be ignored.
> Load key "C:\\path\\to\\hoge.sec": bad permissions
> miyashiro@hoge.example.com: Permission denied (publickey).
> プロセスが、存在しないパイプに書き込もうとしました。
[00:11:26.632] "install" terminal command done
[00:11:26.632] Install terminal quit with output: プロセスが、存在しないパイプに書き込もうとしました。
[00:11:26.632] Received install output: プロセスが、存在しないパイプに書き込もうとしました。
[00:11:26.633] WARN: $PLATFORM is undefined in installation script output.  Errors may be dropped.
[00:11:26.633] Failed to parse remote port from server output
[00:11:26.633] Exec server for ssh-remote+hoge.example.com failed: Error
[00:11:26.633] Existing exec server for ssh-remote+hoge.example.com errored (Error)
[00:11:26.633] Initizing new exec server for ssh-remote+hoge.example.com
[00:11:26.634] Error opening exec server for ssh-remote+hoge.example.com: Error
[00:11:26.634] No hints found in the recent session.

やり方

以下のコマンドで秘密鍵の所有権を自分だけに変更するといけるようになる。

icacls "C:\path\to\hoge.sec" /inheritance:r /grant:r "%USERNAME%:F"

icaclsはファイルの所有権を変更するコマンドで、/inheritance:rで親フォルダからの継承を無効にし、指定したファイルに対する親フォルダから継承した権限を削除し、/grant:r "%USERNAME%:F"でファイルに対する権限を削除し、現ユーザーのフルアクセス権で上書きしている(要するに既存のアクセス権を、現ユーザーのフルアクセス権で置換しているのだと思う)

恐らくLinuxのOpenSSH同様に、WindowsのOpenSSHも鍵をユーザー以外が見れるとだめなのだろう。