linux下免交互工具之expect —— 筑梦之路

1. 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(工具命令语言)来控制程序流和必要的交互。

 2. 安装和使用

# 安装

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和变量

#!/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

猜你喜欢

转载自blog.csdn.net/qq_34777982/article/details/131069875
今日推荐