1. expect syntax
expect [options] [commands/command file]
The Expect program interacts with other programs using the following keywords:
Order | Function |
spawn | Create a new interactive process that starts, followed by a command or specified program process |
send | send a string to the process |
expect | Receive information from the process, if the match is successful, execute the action after expect |
interact | allow user interaction |
set timeout | set timeout |
send_user | Used to print output, equivalent to echo in the shell |
exp_continue | Multiple matches in expect need to be used |
exit | Exit the expect script |
set | define variable |
Expect uses TCL (Tool Command Language) to control program flow and necessary interactions.
2. Installation and use
# 安装
yum install expect
# 脚本首行
#!/usr/bin/expect
# 使用示例
创建交互脚本interactive_script.sh
#!/bin/bash
echo "Hello, who is this?"
read $REPLY
echo "What's your favorite color?"
read $REPLY
echo "How many cats do you have?"
read $REPLY
创建expect脚本expect_response.exp
#!/usr/bin/expect
spawn ./interactive_script.sh
expect "Hello, who is this?\r"
send -- "小明\r"
expect "What's your favorite color?\r"
send -- "蓝色\r"
expect "How many cats do you have?\r"
send -- "1个\r"
expect eof
# 执行
./expect_response.exp
or
expect expect_response.exp
3. Expect and variables
#!/usr/bin/expect
set NAME "Li Ming"
set COLOR "Blue"
set NUMBER [lindex $argv 0]
spawn ./interactive_script.sh
expect "Hello, who is this?\r"
send -- "$NAME\r"
expect "What's your favorite color?\r"
send -- "$COLOR\r"
expect "How many cats do you have?\r"
send -- "$NUMBER\r"
expect eof