expectがわからない

2019-11-9 - 読み終える時間: 3 分

Linuxのコマンド expect について

たとえばpasswdコマンドやsshログインの際に出てくる入力プロンプトに対して応答を自動的に返してくれるシェルインターフェース。それがexpect。

expectでやりたいこと

ipa user-add --password

この時2回のパスワード入力を求められる。プロンプトはこうだ。

Password:

Enter Password again to verify:

これにexpectで応答したい。普通に考えて、以下のように書いた。

#!/bin/bash

userPASS=$1
userID=$2

expect -c "

set timeout 1
spawn env LANG=C ipa user-add \"${userID}\" --first=\"${userID}\" --last=user --password
expect \"Password:\" {
  exp_send -- \"${userPASS}\n\"
}
expect \"Enter Password again to verify: \" {
  exp_send -- \"${userPASS}\n\"
}

exit 0
"

これは2回目のプロンプトでsendされずに止まってしまう。

[AD]2020年プログラミング必修化に先手!家庭で学べるレゴ ロボット。

よくわからないままだが、以下のように2回繰り返す記述をしたら2回目のプロンプトも応答してくれているようだ。

#!/bin/bash

userPASS=$1
userID=$2

expect -c "
set timeout 1
spawn env LANG=C ipa user-add \"${userID}\" --first=\"${userID}\" --last=addrleuser --password
expect \"Password:\" {
  exp_send -- \"${userPASS}\n\"
}
expect \"Password:\" {
  exp_send -- \"${userPASS}\n\"
}
expect \"Enter Password again to verify: \" {
  exp_send -- \"${userPASS}\n\"
}
expect \"Enter Password again to verify: \" {
  exp_send -- \"${userPASS}\n\"
}

exit 0
"

こうすると、1秒のタイムアウトの後パスワードの文字列がsendされ、やりたいこと自体は達成される。 しかし、わけが解らない。

expectのバージョン

$ expect -v
expect version 5.45

いったいexpectの中で何が起こっているというのだろうか?

今日はここまで。