expect的用法

安装

yum install expect -y

关于expect

expect #自动应答命令用于交互式命令的自动执行
spawn  #expect中的监控程序,其运行会监控命令提出的交互式问题
send   #发送问题答案给交互命令
"\r"   #表示回车
exp_continue #当问题不存在时继续回答下边的问题
expect eof   #问题回答完毕退出expect环境
interact     #问题回答完毕留在交互界面
set NAME [ lindex $argv n]  #定义变量

编写一个脚本,为expect的调用做铺垫
vim ask.sh

#! /bin/bash

read -p "What's your name: " NAME
read -p "How old are you:" AGE
read -p "What object do you study: " OBJ
echo "$NAME is $AGE and study $OBJ"

vim answer.exp

#! /usr/bin/expect

set timeout 2

spawn ./ask.sh
expect "name"
send "wangwei\r"
expect "old"
send "23\r"
expect "object"
send "English\r"
expect eof

赋予脚本执行权限并执行

chmod u+x ask.sh 
chmod u+x answer.sh
[testmsgpub@sd-3-centos249 ~]$ ./answer.sh 
spawn ./ask.sh
What's your name: wangwei
How old are you:23
What object do you study: English
wangwei is 23 and study English

交互式回答问题

vi answer.exp

#! /usr/bin/expect

set timeout 2
set NAME [ lindex $argv 0 ]
set OLD [ lindex $argv 1 ]
set OBJ [ lindex $argv 2 ]
spawn ./ask.sh
expect {
        name { send "$NAME\r";exp_continue}
        old { send "$OLD\r";exp_continue }
        obj { send "$OBJ\r"}
}
expect eof

赋予脚本执行权限并执行

chmod u+x ask.sh 
chmod u+x answer.exp
[testmsgpub@sd-3-centos249 ~]$ ./answer.exp sdf 23 dfasd
spawn ./ask.sh
What's your name: sdf
How old are you:23
What object do you study: dfasd
sdf is 23 and study dfasd

注意事项:

1、不能使用bash运行expect脚本

[testmsgpub@sd-3-centos249 ~]$ bash answer.exp 
answer.exp: line 7: spawn: command not found
couldn't read file "{": no such file or directory
answer.exp: line 9: name: command not found
answer.exp: line 9: exp_continue}: command not found
answer.exp: line 10: old: command not found
answer.exp: line 10: exp_continue: command not found
answer.exp: line 11: obj: command not found
answer.exp: line 12: syntax error near unexpected token `}'
answer.exp: line 12: `}'

2、expect最后一个问题不能加exp_continue
expect的用法_第1张图片
否则报错:
expect的用法_第2张图片

参考:https://blog.csdn.net/wzt888_/article/details/80826196

你可能感兴趣的:(Linux,shell脚本)