あいつの日誌β

働きながら旅しています。

ubuntu で useradd したときに password をデフォルトで設定したいので expect を使う

ubuntuadduser を実行すると対話モードが発生します。

USER_NAME=okamuuu # 適宜変更してください
sudo adduser $USER_NAME

こんな感じの対話モードが始まります。

Adding user `okamuuu' ...
Adding new group `okamuuu' (1002) ...
Adding new user `okamuuu' (1002) with group `okamuuu' ...
Creating home directory `/home/okamuuu' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:  # パスワード入力
Retype new UNIX password: # パスワード入力(確認)
passwd: password updated successfully
Changing the user information for okamuuu
Enter the new value, or press ENTER for the default
        Full Name []:    # Enter連打
        Room Number []: 
        Work Phone []: 
        Home Phone []: 
        Other []: 
Is the information correct? [Y/n] Y  # Yes
# 終了

こんな感じの createuser.sh を追加するとよいでしょう。

if [ $# -ne 1 ]; then
  echo "実行するには1個の引数が必要です。" 1>&2
  exit 1
fi

USER_NAME=$1
PASSWORD=hogehogehoge

echo ${USER_NAME}

sudo expect -c "
spawn adduser ${USER_NAME}
expect \"Enter new UNIX password:\"
send -- \"${PASSWORD}\n\"
expect \"Retype new UNIX password:\"
send -- \"${PASSWORD}\n\"
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?\"
send -- \"Y\n\"
interact

こんな感じで実行

sh createuser.sh okamuuu

おしまい。