目的
リモート接続先で任意のコマンドを入力する際、標準入力からパスワードを入力せず、プログラムでログイン処理を自動化する
例
$ ssh hoge@example.com sudo service httpd restart
方法
expectを使用する
設定
インストール
$ sudo yum -y install expect
sudoers
コメントアウトする
# Defaults specification
自動化プログラム
auto_login
#!/bin/sh
auto_login() {
host=$1
id=$2
pass=$3
expect -c "
set timeout 10
spawn ssh ${id}@${host} sudo service httpd restart
#ログインしたいだけなら、引数なし
#spawn ssh ${id}@${host}
expect \"Are you sure you want to continue connecting (yes/no)?\" {
send \"yes\n\"
expect \"${id}@${host}'s password:\"
send \"${pass}\n\"
} \"${id}@${host}'s password:\" {
send \"${pass}\n\"
}
interact
"
}
ssh_secondary
#!/bin/sh
set -x
# shスクリプト読込
. /home/vagrant/auto_login
# 自動ログイン実行
auto_login '***.***.***.***' 'vagrant' 'vagrant'
デバッグ
[vagrant@primary ~]$ sudo ./ssh_secondary
+ . /home/vagrant/auto_login
+ auto_login ***.***.***.***[secondary-IP] vagrant vagrant
+ host=***.***.***.***[secondary-IP]
+ id=vagrant
+ pass=vagrant
+ set -x
+ expect -c '
set timeout 10
#spawn ssh vagrant@***.***.***.***[secondary-IP]
spawn ssh vagrant@***.***.***.***[secondary-IP] sudo service httpd restart
expect "Are you sure you want to continue connecting (yes/no)?" {
send "yes\n"
expect "vagrant@***.***.***.***[secondary-IP]'\''s password:"
send "vagrant\n"
} "vagrant@***.***.***.***[secondary-IP]'\''s password:" {
send "vagrant\n"
}
interact
'
spawn ssh vagrant@***.***.***.***[secondary-IP] sudo service httpd restart
vagrant@***.***.***.***[secondary-IP]'s password:
Stopping httpd: [ OK ]
Starting httpd: [ OK ]
[vagrant@primary ~]$
プログラムの中にアイパスを書いてるので、利用はInternalで