LoginSignup
1
0

More than 3 years have passed since last update.

sshpass+ssh-copy-idで公開鍵をインストールする方法

Last updated at Posted at 2019-11-25

sshpassとは

sshpass(1) - Linux man page
noninteractive ssh password provider

プロンプトを使用せずにCLIにパスワードを渡してSSHすることができる方法である。
連続してパスワード認証したいとき等に便利である。
※ そもそも、そのような状態には出くわしたくないが(鍵認証onlyなどの対策)、状況によっては大量のサーバへ接続するなどのときに便利なときもある。

macOS に Homebrew で sshpass をインストールする - Qiita

Macでsshpassいれる際はこちらの対応が参考になった。
他参考:Installing SSHPass

事前準備。
homebrewで最新をいれたいときには参考になる。
とりあえずお試しで入れるには以下で十分。

brew install http://git.io/sshpass.rb
brew install sshpass

sshpassを使うことができるようになる。

ssh-copy-id

公開鍵を登録して認証するとパスワードなしでSSH可能な状態を作ることができる。
そこで、sshの公開鍵鍵認証登録に便利なのが ssh-copy-id
ssh-copy-id(1) - Linux man page

ssh-copy-id
% ssh-copy-id -i ~/.ssh/id.pub hoge.example
/usr/local/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/hoge/.ssh/id.pub"
/usr/local/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/local/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
hoge@hoge.example's password:

Number of key(s) added:        1

Now try logging into the machine, with:   "ssh 'hoge.example'"
and check to make sure that only the key(s) you wanted were added.

この鍵を登録する際にパスワード認証が上記のように必要だが、一度入力するとその後は
ssh hoge.example のときに手元の秘密鍵を使えばパスワードなしで接続が可能になる。

なお、ここで紹介した認証に必要な鍵は ssh-keygen で作成済みとする。
参考:お前らのSSH Keysの作り方は間違っている - Qiita

sshpass + ssh-copy-id

上記のパターンで事前に公開鍵登録ができていないサーバが複数台あったとする。
そのときにパスワード入力を仕方なく入力するときに sshpass と連携すると便利というのが本題。

ssh-pass+ssh-coyp-id
sshpass -f passwd ssh-copy-id -i ~/.ssh/id.pub -o "StrictHostKeyChecking no" hoge.example

このとき、 (yes/no)を聞かれる定番の対策に -o "StrictHostKeyChecking no" を使っている。
-f passwd はpasswdファイルというものを用意してパスワードを記載している場合。変数や直接入力も可能。

これで、対象のホストが複数あるときはwhileなりfor文なりでワンライナーでリストや対象ホストの連番へアクセスしてssh-copy-idを連続して登録ということができる。

1
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
1
0