15
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

expectを利用したssh接続時のパスワード入力の自動化

Last updated at Posted at 2015-09-30

##目的
リモート接続先で任意のコマンドを入力する際、標準入力からパスワードを入力せず、プログラムでログイン処理を自動化する

$ ssh hoge@example.com sudo service httpd restart

##方法
expectを使用する

##設定
###インストール
$ sudo yum -y install expect

###sudoers
コメントアウトする
# Defaults specification


###自動化プログラム ```bash: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
"
}


```bash: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で

15
18
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
15
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?