LoginSignup
214
216

More than 5 years have passed since last update.

対話式のコマンドをスクリプト化する方法

Last updated at Posted at 2014-10-21

れれ?? Qiitaのフォント変わった?

さて、今日はexpectを使います。

expectコマンドとは

コマンドの返答を識別して次の入力を自動的に行うコマンドー

expect -c "
spawn [実行したいコマンド]
expect [コマンドの返答]
send -- [次のコマンド]
"

といった感じで使います。

実装例1:Linuxにユーザーを追加

利用するコマンド

  • expect
  • useradd
  • passwd

事前にexpectをインストール

yum install expect

シェルスクリプトを作成

set_user.sh
#!/usr/bin

useradd UserName 
expect -c "
spawn passwd UserName
expect \"New password:\"
send -- \"hogehoge\n\"
expect \"Retype new password:\"
send -- \"hogehoge\n\"
expect \"passwd: all authentication tokens updated successfully.\"
send -- \"exit\n\"
"

で、実行

$ chmod +x set_passwd.sh 
$ ./set_passwd.sh 

実装例2:CSVのデータを元にLinuxにユーザーを追加

仕様

  1. [ユーザー名]と[パスワード]をCSVに記入
  2. csv内の値を引数に、useradd, passwdを順次実行

実装

ユーザーとパスワードをhoge.csvに記入
こんな時vim便利ね☆

hoge.csv
user1,hogehoge
user2,fugafuga
user3,hafuhafu
user4,puripuri

シェルスクリプトを作成

set_user.sh
#!/usr/bin/
csvfile=hoge.csv
for line in `cat ${csvfile} | grep -v ^#`
do
    user=`echo ${line} | cut -d ',' -f 1`
    pass=`echo ${line} | cut -d ',' -f 2`
    useradd $user
    expect -c "
    spawn passwd ${user}
    expect \"New password:\"
    send -- \"${pass}\n\"
    expect \"Retype new password:\"
    send -- \"${pass}\n\"
    expect \"passwd: all authentication tokens updated successfully.\"
    send -- \"exit\n\"
    "
done

で、実行

$ chmod +x set_passwd.sh 
$ ./set_passwd.sh 

以上

追記

本当はLinuxのユーザーのパスワードを200件ほど書き換えたくて効率的な方法を探していた。。
今回はexportを利用したが、記事を書き終えてすぐ chpasswdなるコマンドーの存在を知っていま絶望している........。。。。。

chpasswd < testpass.txt

参考:ユーザパスワード一括変更 ~Linux編~

214
216
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
214
216