EC2のユーザデータでadduserコマンドを使いたいが対話モードで入力が必要。そこでexpectコマンドを使って自動で対話モード入力を行ってみることにした。expectコマンドを使ったスクリプトscript.sh
を作成する。script.sh
を作成した後、chmodで実行権限を付与するのを忘れないこと。
chmod +x script.sh
./script.sh
script.sh
の中身は以下の通り。以下の例ではユーザ名が「test123」、パスワードが「test」としている。パスワード入力後に少し待たないとうまくいかないので、set timeout 3
を入れている。
script.sh
# !/bin/bash
expect -c "
spawn sudo adduser test123
expect \"New password:\"
send \"test\n\"
expect \"Retype new password:\"
send \"test\n\"
set timeout 3
expect \"Full Name []:\"
send \"\n\"
expect \"Room Number []:\"
send \"\n\"
expect \"Work Phone []:\"
send \"\n\"
expect \"Home Phone []:\"
send \"\n\"
expect \"Other []:\"
send \"\n\"
expect \"Is the information correct? \[Y\/n\]\"
send \"Y\n\"
interact
"