12
14

More than 5 years have passed since last update.

`sshpass` で秘密鍵のパスフレーズを自動入力する

Last updated at Posted at 2018-11-03

パスフレーズ付きの秘密鍵を必要とする SSHサーバーの設定で、SSHのログインを sshpass を用いて自動化したかったのですが、
単純に sshpass -f ./key_password ssh <options> と実行するだけでは、パスフレーズの入力が求められるままでした。

SSH/SCP のログイン自動化に sshpass が便利すぎた - CUBE SUGAR CONTAINER
https://blog.amedama.jp/entry/2017/06/03/131852

解決法: パスフレーズ入力のプロンプトを検出できるようにする

今回の原因は、 パスフレーズ入力を求める表示(プロンプト)が sshpass で検出できなかったことです。
この場合は -P "Enter passphrase for key" のオプションをつけましょう。

$ sshpass -f ./key_password -P "Enter passphrase for key" ssh -o StrictHostKeyChecking=no -i ./id_rsa user@localhost

ssh -o StrictHostKeyChecking=no -i ./id_rsa user@localhostsshpass を使わない場合と同じSSHのコマンドになります。
sshpass が関わる部分はこれよりも前になります。

-o StrictHostKeyChecking=no をつけるようにしましょう。

-P オプションについて

-P オプションについては sshpass の使い方に書いてあります 💡

$ sshpass
Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
   -f filename   Take password to use from file
   -d number     Use number as file descriptor for getting password
   -p password   Provide password as argument (security unwise)
   -e            Password is passed as env-var "SSHPASS"
   With no parameters - password will be taken from stdin

   -P prompt     Which string should sshpass search for to detect a password prompt
   -v            Be verbose about what you're doing
   -h            Show help (this screen)
   -V            Print version information
At most one of -f, -d, -p or -e should be used

sshpass を用いずにSSHでログインすると、秘密鍵のパスフレーズを入力するプロンプトは次のように表示されました。

Enter passphrase for key './id_rsa':

この表示が sshpass で想定されているモノと違うようなので、コレを -P オプションでマッチさせると sshpass がパスフレーズを入力してくれるようになります 😀

12
14
2

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
12
14