Linux中通过expect工具实现脚本的自动交互
Bash 脚本提供了许多程序和功能来执行系统自动化任务。expect 命令提供了一种方法来控制需要用户输入才能继续的交互式应用程序。
expect语法
expect [options] [commands/command file]
Expect 程序使用以下关键字与其他程序进行交互:
| 命令 | 功能 |
|---|---|
| spawn | 创建一个启动新的交互进程, 后面跟命令或者指定程序进程 |
| send | 向进程发送字符串 |
| expect | 从进程中接收信息, 如果匹配成功, 就执行expect后的动作 |
| interact | 允许用户交互 |
| set timeout | 设置超时时间 |
| send_user | 用来打印输出,相当于shell中的echo |
| exp_continue | 在expect中多次匹配就需要用到 |
| exit | 退出expect脚本 |
| set | 定义变量 |
Expect 使用 TCL(工具命令语言)来控制程序流和必要的交互。
安装(redhat)
yum install expect
脚本的开头
#!/usr/bin/expect
找到安装路径的命令
whereis 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
或者:
expect expect_response.exp

expect和变量
#!/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
运行后所得结果:

浙公网安备 33010602011771号