expect用法

今天学shell脚本的时候,看到了expect,本来想随便了解一下好了,以后有用了再看,但是后来想了想还是好好看看吧,嘿嘿,然后百度呀啥的,有一篇文章推荐了http://www.thegeekstuff.com/2010/10/expect-examples/  英文的,以前很有心理压力,一看到英文的,今天不知咋地,想看看,一看,发现只有自己认真的看,再加上Google翻译,还是可以看懂的。就把自己学的看的总结一下,写博客的时候,有时要选原创啊,转载啊,其实很多时候分不清原创的具体定义是啥,看着文档,看着书,然后自己做的总结不知是不是?

1:有三个命令

    send – to send the strings to the process
    expect – wait for the specific string from the process
    spawn – to start the command

2:hello world初试,vim expect1.exp  

#/usr/bin/expect
#filename expect1.sh
#expect实验 交互式输入输出,执行脚本后,当你输入hello的时候,它会自动输出world

expect "hello"
send "world"             

       这个地方纠结了好久,因为一直用的是expect.sh ,然后执行的时候也是sh expect.sh,后来仔细看文档才发现    Generally, expect script files has .exp as extensions 这一句。执行的时候也是 expect expect1.exp

       执行的时候,若输入的不是他期望的值,他会一直让你输

       我的理解: 如果输入的值和expect期望的值一样,就send返回一个设定的值

3:设置输入时,超时的时间  

#/usr/bin/expect
#filename expect2.exp
#交互输入输出的时候,如果你超过多少时间,那么将直接输出返回的值
set timeout 10
expect "hello"
send "world
"

    当执行脚本后,若10s没有输入任何东西,那么将直接输出send值。

4:Automate User Processes With Expect  和进程进行交互?(解释不出那种感觉)

addtion脚本:

#!/bin/bash
#filename addtion.sh

read -p "Enter the number1:" no;
read -p "Enter the number2:" no2;
let result=$no+$no2
echo "result:$result"

expect.exp脚本:

#!/usr/bin/expect
#filename addition.exp
#和addtion.sh进行交互

set timeout 20

spawn sh addtion.sh

expect "Enter the number1:" { send "12
" }
expect "Enter the number2:" { send "23
" }

interact

spawn:用来启动一个新的进程,和addtion.sh进行交互,spawn后的expect和send都是在新的启动的进程addtion.sh进行交互的。

当addtion.sh有输出Enter the number1:的时候,就send12,

当addtion.sh有输出Enter the number2:的时候,就send23

5:练习,比如ssh 上jenkins@f1.y的时,不用输密码,自己自动连接上

#!/usr/bin/expect
#filename:ssh.exp
#ssh的时候自动输入密码连接上

spawn ssh jenkins@f1.y

expect "password:" { send "jenkins.123
" }
interact

当ssh jenkins@f1.y的时候,会有一个输出信息,要输入密码,在当匹配到password的时候,send密码进去,就自动连接上了

interact:连接上后,用户还可以自己进行操作,如果没有的话,就直接退回到原来的状态了。也就是执行完里面的操作,又回到原始状态

6:

match.exp

#!/usr/bin/expect
#filename:match.exp
#$expect_out(buffer)与$expect_out(0,string)

set timeout 20

spawn sh he.sh

expect "hello"
puts stderr "no match:  $expect_out(buffer) 
"
puts stdout  "match :  $expect_out(0,string) 
"

interact          

he.sh

#!/bin/bash

echo "Sh program";
echo "hello world";
$expect_out(buffer)   :匹配之前的存放的位置
$expect_out(0,string) :匹配的存放的地方
 
例子:
#!/usr/bin/expect

set ip "10.0.0.142"
set user "root"
set password "123456"

spawn ssh $user@$ip
expect {
"yes/no" { send "yes
";exp_continue }
"password:" { send "$password
" }
}
interact


 
原文地址:https://www.cnblogs.com/lemon-le/p/5797948.html