プログラムがユーザー入力を要求するときは、ユーザーの操作なしで応答を送信することを期待してください。
インストール
UbuntuのようなDebianaptベースのシステム
sudo apt update
sudo apt install -y expect CentosのようなRedHatベースのシステム
# Centos 7
sudo yum install -y expect
# Centos 8
sudo dnf install -y expect Expectコマンドの場所に関するエラーが発生した場合は、whichコマンドを使用して場所を取得できます。
which expect
which autoexpect 例
これをname.shに保存します
#!/bin/bash
echo "What is your name?"
read name
echo "Your name is ${name}" スクリプトを実行可能にします:
chmod +x name.sh
# Execute
./name.sh
スクリプトを手動で実行すると、What is your name?で名前を入力するように求められます。 入力すると印刷されます。
expectを使用できます クエリへの自動応答を提供します。スクリプトは次のとおりです:
これをauto.expに保存します
#!/usr/bin/expect
set timeout -1
spawn ./name.sh
expect "What is your name?\r"
send -- "John\r"
expect eof 読みやすく実行可能にする:
chmod +x auto.exp
これは、スクリプトが./auto.expで実行されたときの出力です。 :
➜ ./auto.exp
spawn ./name.sh
What is your name?
John
Your name is John 変数の操作
setコマンドを使用して、次のようなexpectスクリプトで変数を定義できます。
set user kip
set age 10
変数にアクセスするには、その前に$を付けます bashのように(例:$user )
期待スクリプトでコマンドライン引数を定義するには、次の構文を使用します。
set USER [lindex $argv 0] ここでは、最初に渡された引数に等しい変数USERを定義します。
最初と2番目の引数を取得して、次のような変数に格納できます。
set USER [lindex $argv 0]
set PASSWORD [lindex $argv 1] 変数を使用したスクリプトの例
スクリプトを作成せずにそれを実行する別の方法:
sftpパスワードを変更する例。これらを./sftp_password_change.expに保存します 。
#!/usr/bin/expect
set timeout 10
set curpass [lindex $argv 0];
set newpass [lindex $argv 1];
set user [lindex $argv 2];
set server [lindex $argv 3];
expect <<EOF
spawn sftp -P 15422 [email protected]$server
expect "Password:"
send "$curpass\r"
expect "Old Password:"
send "$curpass\r"
expect "New Password:"
send "$newpass\r"
expect "Reenter New Password:"
send "$newpass\r"
expect "sftp>"
send "exit\n" でsctiptを実行します
./sftp_password_change.exp $curpass $newpass $user $server 自動期待
autoexpect コマンドを使用すると、スクリプトを引数として指定できます。その後、スクリプトが作成されます。
autoexpect ./installappなどのコマンドを使用すると、指定した回答を使用してexpectスクリプトが作成されます。
$ autoexpect ./name.sh
autoexpect started, file is script.exp
What is your name?
John
Your name is John
autoexpect done, file is script.exp
結果のscript.exp ファイルには、autoexpectで作成されたという説明が含まれ、提供された応答が含まれます。
autoexpectツールは、インストールを非対話的に実行するためのスクリプトを準備します。その後、詳細を提供したり、自分で実行するようにスケジュールしたりせずに、インストールを実行できます。
これはコメントなしで生成されたコンテンツです
$ cat script.exp
#!/usr/bin/expect -f
#
set force_conservative 0 ;# set to 1 to force conservative mode even if
;# script wasn't run conservatively originally
if {$force_conservative} {
set send_slow {1 .1}
proc send {ignore arg} {
sleep .1
exp_send -s -- $arg
}
}
set timeout -1
spawn ./name.sh
match_max 100000
expect -exact "What is your name?\r
"
send -- "John\r"
expect eof 結論
expect commandは、長い一連の回答を必要とするスクリプトを実行するのに便利であり、無人で実行できます。autoexpectを使用すると、構文の詳細にストレスをかけることなく、expectスクリプトを簡単に作成できます。