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も鍵をユーザー以外が見れるとだめなのだろう。

2025/09/30(火)GitHubのリポジトリをSSH認証経由で扱えるようにする

更新日:
投稿日:

なんか突如としてGitHubにHTTP経由で繋ぐのが面倒くさくなったのでSSHで繋げるようにしたときのメモ。

確認環境

  • Windows 11 Pro 25H2
  • Ubuntu 24.04.3 LTS
  • RLogin 2.30.8

やり方

SSH鍵の作成

  1. RLoginを開き、サーバーに接続→新規→サーバー→プロトコルを開く
  2. 認証キーボタンを押しED25519辺りで適当な名前で鍵を作成する
  3. 適当な場所に秘密鍵をエクスポートする。ここでは便宜上github.secとする
  4. 鍵を右クリックし、公開鍵をコピーして、どっかにメモっておく

GitHubへの登録

  1. GitHubを開き、アカウント設定に移動、SSH and GPG keysを開く
  2. SSH keys→New SSH Keyを開く
  3. Titleに適当な名前を設定
  4. Key typeはAuthentication Keyにする
  5. RLoginで作った
  6. コピーした公開鍵をKeyに貼り付ける
  7. Add SSH keyボタンを押す

鍵束へのSSH鍵の登録

Windowsの場合

忘れた。

Ubuntuの場合

正攻法では以下だが、keychainを使ったほうが運用が楽。

# 鍵束への登録
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/github.sec

# 接続確認
ssh -T git@github.com

SSH Configを書く

Windowsの場合

ここではWindowsのSSHクライアントを利用する。

  1. Gitに利用するSSHクライアントの設定をする
    git config --global core.sshCommand "C:/Windows/System32/OpenSSH/ssh.exe"
    
  2. 作成したSSH鍵をC:/Users/<ユーザー名>/.ssh/に置く
  3. C:/Users/<ユーザー名>/.ssh/configを開き、次の内容を記述
    Host github.com
        User <ユーザーID>
        Hostname github.com
        IdentityFile C:/Users/<ユーザー名>/.ssh/github.sec
    
    パス表現に%USERPROFILE%は通用しないので注意
Ubuntuの場合
  1. 作成したSSH鍵を~/.ssh/github.secに置く
  2. chmod 600 ~/.ssh/github.secとかして自分しか見れないようにする
  3. ~/.ssh/configを開き、次の内容を記述
    Host github.com
        User <ユーザーID>
        Hostname github.com
        IdentityFile ~/.ssh/github.sec
    

既存のリポジトリをSSH対応にする

ここではoriginがリモートであるとして進める。

  1. git remote -vでリモートリポジトリの状況を確認
  2. git remote remove originでHTTP通信になってるのを消す
  3. git remote add origin git@github.com:Hoge/piyo.gitでSSH通信に書き換える
  4. git fetchが通ればOK

トラブルシューティング

Permission Denied (publickey)が出る

  1. 鍵のパーミッションが600、.ssh/のパーミッションが700なのを確認する
  2. ssh -T git@github.comで繋がるか確認する。繋がらなければこれまでの手順が何か漏れないか確認する
  3. ユーザー名が間違っていても出る

2024/03/03(日)Windows 11でパスフレーズ付きの公開鍵認証SFTPをマウントする

更新日:
投稿日:

古のSFTPマウントツールが軒並み死んでいるためRcloneを使う。WindowsからLinux上に構築したストレージに繋ぐときに便利。

前提条件

  • 接続先のSSH環境がある
  • 接続先のSSH環境の公開鍵認証に利用する秘密鍵にパスフレーズが付いている

確認環境

Env Ver
OS Windows 11 Home 25H2(26200.8039)
Rclone 1.73.3

手順

1. 基本環境のインストール

  1. Rcloneをインストールする
    choco install rclone
    
  2. WinFspもインストールする。これがないとマウントできない

2. マウント設定の作成

  1. 次のコマンドで設定ウィザードを起動する
    rclone config
    
  2. 設定はこんな感じ

    # 新しい設定ファイルの作成
    No remotes found, make a new one?
    n) New remote
    s) Set configuration password
    q) Quit config
    n/s/q>n
    
    # 接続名を設定する
    Enter name for new remote.
    name> hoge
    
    # 接続先のストレージ種別をSSHで設定する
    Option Storage.
    Type of storage to configure.
    Choose a number from below, or type in your own value.
    1 / 1Fichier
    \ (fichier)
    2 / Akamai NetStorage
    \ (netstorage)
    3 / Alias for an existing remote
    \ (alias)
    4 / Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, BizflyCloud, Ceph, ChinaMobile, Cloudflare, Cubbit, DigitalOcean, Dreamhost, Exaba, FileLu, FlashBlade, GCS, Hetzner, HuaweiOBS, IBMCOS, IDrive, Intercolo, IONOS, Leviia, Liara, Linode, LyveCloud, Magalu, Mega, Minio, Netease, Outscale, OVHcloud, Petabox, Qiniu, Rabata, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Servercore, SpectraLogic, StackPath, Storj, Synology, TencentCOS, Wasabi, Zata, Other
    \ (s3)
    5 / Backblaze B2
    \ (b2)
    6 / Better checksums for other remotes
    \ (hasher)
    7 / Box
    \ (box)
    8 / Cache a remote
    \ (cache)
    9 / Citrix Sharefile
    \ (sharefile)
    10 / Cloudinary
    \ (cloudinary)
    11 / Combine several remotes into one
    \ (combine)
    12 / Compress a remote
    \ (compress)
    13 / DOI datasets
    \ (doi)
    14 / Drime
    \ (drime)
    15 / Dropbox
    \ (dropbox)
    16 / Encrypt/Decrypt a remote
    \ (crypt)
    17 / Enterprise File Fabric
    \ (filefabric)
    18 / FTP
    \ (ftp)
    19 / FileLu Cloud Storage
    \ (filelu)
    20 / Filen
    \ (filen)
    21 / Files.com
    \ (filescom)
    22 / Gofile
    \ (gofile)
    23 / Google Cloud Storage (this is not Google Drive)
    \ (google cloud storage)
    24 / Google Drive
    \ (drive)
    25 / Google Photos
    \ (google photos)
    26 / HTTP
    \ (http)
    27 / Hadoop distributed file system
    \ (hdfs)
    28 / HiDrive
    \ (hidrive)
    29 / ImageKit.io
    \ (imagekit)
    30 / In memory object storage system.
    \ (memory)
    31 / Internet Archive
    \ (internetarchive)
    32 / Internxt Drive
    \ (internxt)
    33 / Jottacloud
    \ (jottacloud)
    34 / Koofr, Digi Storage and other Koofr-compatible storage providers
    \ (koofr)
    35 / Linkbox
    \ (linkbox)
    36 / Local Disk
    \ (local)
    37 / Mail.ru Cloud
    \ (mailru)
    38 / Mega
    \ (mega)
    39 / Microsoft Azure Blob Storage
    \ (azureblob)
    40 / Microsoft Azure Files
    \ (azurefiles)
    41 / Microsoft OneDrive
    \ (onedrive)
    42 / OpenDrive
    \ (opendrive)
    43 / OpenStack Swift (Rackspace Cloud Files, Blomp Cloud Storage, Memset Memstore, OVH)
    \ (swift)
    44 / Oracle Cloud Infrastructure Object Storage
    \ (oracleobjectstorage)
    45 / Pcloud
    \ (pcloud)
    46 / PikPak
    \ (pikpak)
    47 / Pixeldrain Filesystem
    \ (pixeldrain)
    48 / Proton Drive
    \ (protondrive)
    49 / Put.io
    \ (putio)
    50 / QingCloud Object Storage
    \ (qingstor)
    51 / Quatrix by Maytech
    \ (quatrix)
    52 / Read archives
    \ (archive)
    53 / SMB / CIFS
    \ (smb)
    54 / SSH/SFTP
    \ (sftp)
    55 / Shade FS
    \ (shade)
    56 / Sia Decentralized Cloud
    \ (sia)
    57 / Storj Decentralized Cloud Storage
    \ (storj)
    58 / Sugarsync
    \ (sugarsync)
    59 / Transparently chunk/split large files
    \ (chunker)
    60 / Uloz.to
    \ (ulozto)
    61 / Union merges the contents of several upstream fs
    \ (union)
    62 / WebDAV
    \ (webdav)
    63 / Yandex Disk
    \ (yandex)
    64 / Zoho
    \ (zoho)
    65 / iCloud Drive
    \ (iclouddrive)
    66 / premiumize.me
    \ (premiumizeme)
    67 / seafile
    \ (seafile)
    Storage> 54
    
    # 接続先のホストを設定
    Option host.
    SSH host to connect to.
    E.g. "example.com".
    Enter a value.
    host> ssh.example.com
    
    # 接続先のユーザー名を設定
    Option user.
    SSH username.
    Enter a value of type string. Press Enter for the default (MYPC\myuser).
    user> hoge
    
    # 接続先のポートを指定、デフォルトならエンターで飛ばせると思う
    Option port.
    SSH port number.
    Enter a signed integer. Press Enter for the default (22).
    port> 12345
    
    # 鍵認証なのでエンターで飛ばす
    Option pass.
    SSH password, leave blank to use ssh-agent.
    Choose an alternative below. Press Enter for the default (n).
    y) Yes, type in my own password
    g) Generate random password
    n) No, leave this optional password blank (default)
    y/g/n>
    
    # エンターで飛ばす
    Option key_pem.
    Raw PEM-encoded private key.
    Note that this should be on a single line with line endings replaced with '\n', eg
        key_pem = -----BEGIN RSA PRIVATE KEY-----\nMaMbaIXtE\n0gAMbMbaSsd\nMbaass\n-----END RSA PRIVATE KEY-----
    This will generate the single line correctly:
        awk '{printf "%s\\n", $0}' < ~/.ssh/id_rsa
    If specified, it will override the key_file parameter.
    Enter a value. Press Enter to leave empty.
    key_pem>
    
    # 秘密鍵のパスを指定
    Option key_file.
    Path to PEM-encoded private key file.
    Leave blank or set key-use-agent to use ssh-agent.
    Leading `~` will be expanded in the file name as will environment variables such as `${RCLONE_CONFIG_DIR}`.
    Enter a value. Press Enter to leave empty.
    key_file> C:\path\to\hoge.sec
    
    # 秘密鍵のパスフレーズを入れる
    Option key_file_pass.
    The passphrase to decrypt the PEM-encoded private key file.
    Only PEM encrypted key files (old OpenSSH format) are supported. Encrypted keys
    in the new OpenSSH format can't be used.
    Choose an alternative below. Press Enter for the default (n).
    y) Yes, type in my own password
    g) Generate random password
    n) No, leave this optional password blank (default)
    y/g/n> y
    Enter the password:
    password:
    Confirm the password:
    password:
    
    # エンターで飛ばす
    Option pubkey.
    SSH public certificate for public certificate based authentication.
    Set this if you have a signed certificate you want to use for authentication.
    If specified will override pubkey_file.
    Enter a value. Press Enter to leave empty.
    pubkey>
    
    # エンターで飛ばす
    Option pubkey_file.
    Optional path to public key file.
    Set this if you have a signed certificate you want to use for authentication.
    Leading `~` will be expanded in the file name as will environment variables such as `${RCLONE_CONFIG_DIR}`.
    Enter a value. Press Enter to leave empty.
    pubkey_file>
    
    # エンターで飛ばす
    Option key_use_agent.
    When set forces the usage of the ssh-agent.
    When key-file is also set, the ".pub" file of the specified key-file is read and only the associated key is
    requested from the ssh-agent. This allows to avoid `Too many authentication failures for *username*` errors
    when the ssh-agent contains many keys.
    Enter a boolean value (true or false). Press Enter for the default (false).
    key_use_agent>
    
    # エンターで飛ばす
    Option use_insecure_cipher.
    Enable the use of insecure ciphers and key exchange methods.
    This enables the use of the following insecure ciphers and key exchange methods:
    - aes128-cbc
    - aes192-cbc
    - aes256-cbc
    - 3des-cbc
    - diffie-hellman-group-exchange-sha256
    - diffie-hellman-group-exchange-sha1
    Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
    This must be false if you use either ciphers or key_exchange advanced options.
    Choose a number from below, or type in your own boolean value (true or false).
    Press Enter for the default (false).
    1 / Use default Cipher list.
    \ (false)
    2 / Enables the use of the aes128-cbc cipher and diffie-hellman-group-exchange-sha256, diffie-hellman-group-exchange-sha1 key exchange.
    \ (true)
    use_insecure_cipher>
    
    # エンターで飛ばす
    Option disable_hashcheck.
    Disable the execution of SSH commands to determine if remote file hashing is available.
    Leave blank or set to false to enable hashing (recommended), set to true to disable hashing.
    Enter a boolean value (true or false). Press Enter for the default (false).
    disable_hashcheck>
    
    # エンターで飛ばす
    Option ssh.
    Path and arguments to external ssh binary.
    Normally rclone will use its internal ssh library to connect to the
    SFTP server. However it does not implement all possible ssh options so
    it may be desirable to use an external ssh binary.
    Rclone ignores all the internal config if you use this option and
    expects you to configure the ssh binary with the user/host/port and
    any other options you need.
    **Important** The ssh command must log in without asking for a
    password so needs to be configured with keys or certificates.
    Rclone will run the command supplied either with the additional
    arguments "-s sftp" to access the SFTP subsystem or with commands such
    as "md5sum /path/to/file" appended to read checksums.
    Any arguments with spaces in should be surrounded by "double quotes".
    An example setting might be:
        ssh -o ServerAliveInterval=20 user@example.com
    Note that when using an external ssh binary rclone makes a new ssh
    connection for every hash it calculates.
    Enter a value of type SpaceSepList. Press Enter to leave empty.
    ssh>
    
    # エンターで飛ばす
    Edit advanced config?
    y) Yes
    n) No (default)
    y/n>
    
    # 設定内容に問題ないことを確認してエンターで飛ばす
    # 設定を直す場合はeを選ぶと、ここまでの設定内容から修正したい箇所だけ編集できて便利
    Configuration complete.
    Options:
    - type: sftp
    - host: ssh.example.com
    - user: hoge
    - port: 12345
    - key_file: C:\path\to\hoge.sec
    - key_file_pass: *** ENCRYPTED ***
    Keep this "hoge" remote?
    y) Yes this is OK (default)
    e) Edit this remote
    d) Delete this remote
    y/e/d>
    
    # 設定の登録結果が出てくるので、特になければqで終わる
    Current remotes:
    
    Name                 Type
    ====                 ====
    hoge                 sftp
    
    e) Edit existing remote
    n) New remote
    d) Delete remote
    r) Rename remote
    c) Copy remote
    s) Set configuration password
    q) Quit config
    e/n/d/r/c/s/q> q
    
  3. 設定が完了したら、以下のコマンドでマウントできる
    # 例:rclone mount hoge: Z: --network-mode
    # マウントパスを指定する場合はhoge:/path/toのようにすればよいと思うが試してない
    rclone mount <config name>:<mount path> <drive letter>: --network-mode
    

設定ファイルの在り処と中身

一回作った設定ファイルは持ち運べるし、手組もできるのでフォーマットが分かっていれば一々設定ウィザードを起動する必要はない。

  • 設定ファイルの在り処
    • %USERPROFILE%\AppData\Roaming\rclone\rclone.conf
  • 中身のフォーマットはiniファイルで接続先がWindowsのSSHだとshell_typecmd、UbuntuのSSHだとunixとなっていた

    [hoge]
    type = sftp
    host = ssh1.example.com
    user = foo
    port = 12121
    key_file = C:\path\to\hoge.sec
    key_file_pass = XXXXXXXXXXXXXX
    shell_type = cmd
    
    [piyo]
    type = sftp
    host = ssh2.example.com
    user = bar
    port = 12122
    key_file = C:\path\to\piyo.sec
    key_file_pass = YYYYYYYYYYYYYY
    shell_type = unix
    

トラブルシューティング

マウント時のターミナルウィンドウが邪魔

公式の解説によると、Windowsではバックグラウンドで動かすことができない

Use the --daemon flag to force background mode. On Windows you can run mount in foreground only, the flag is ignored.

どうしてもバックグラウンドで動かしたい場合はVDeskを使って適当な仮想デスクトップで起動するか、タスクトレイ系のユーティリティを使ってタスクトレイに突っ込んだりすると良さそうだ。

私は必要なときに都度起動し、仮想デスクトップを作って、そこに避難させとけば良いかな程度で今のところ考えている。この手のはネットワークが不安定な場所で動かすと色々面倒だし、使う頻度も低いので、今はそれで良いかなという感じ。

参考

2023/12/05(火)SSH Configの書き方

更新日:
投稿日:

基本のフォーマット

複数のホストを記述でき ssh <Host> で接続できる

Host hoge
   User foo
   Hostname git1.example.com
   IdentityFile ~/.ssh/config/id_ed25519_foo
   Port 22222
Host piyo
   User bar
   Hostname git2.example.com
   IdentityFile ~/.ssh/config/id_ed25519_bar
   Port 20202

設定項目

項目 意味合い
Host sshコマンドで指定する接続先名。Gitで利用する場合はHostnameと合わせる必要がある
User ログインするユーザー名
Hostname 接続先のホスト名
IdentityFile 秘密鍵のパス
Port 接続先のポート
ForwardAgent プロキシサーバー側の設定。クライアントからの接続を中継するかどうか
ProxyCommand 踏み台サーバーへの接続コマンド

トラブルシューティング

GitHubにSSHで繋ぎに行ったときにError: Permission denied (publickey)と出る

GitHubへのSSH接続はUsergitでなければならない

そういえばgitコマンドはユーザー名を直に指定しているのかSSH Configでgit以外を指定していても通った気がする

GitHubにSSH接続しているときにgit clonegit pushがフリーズする

Hostの値がHostnameと異なるとフリーズすることがある

関連記事