使用Expect自动执行彼此交互的2个脚本 [英] Automate 2 scripts interacting with each others using expect

查看:43
本文介绍了使用Expect自动执行彼此交互的2个脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个简单的脚本,我需要它们使用第三个 expect 脚本

I have 2 simple scripts that I need them to automatically interact with each others using a third expect script

script1.sh

#!/bin/bash

echo "s1: started"
echo "question1"
read
echo "got ${REPLY}"
echo "question2"
read
echo "got ${REPLY}"
echo "question3"
read
echo "got ${REPLY}"
echo "s1: finished"

script2.sh

#!/bin/bash

echo "s2: started"
read
echo "got ${REPLY}"
echo "answer1"
read
echo "got ${REPLY}"
echo "answer2"
read
echo "got ${REPLY}"
echo "answer3"
echo "s2: finished"

auto_s1_s2.exp

#!/usr/bin/expect

spawn -noecho ./script1.sh
set s1ID $spawn_id

spawn -noecho ./script2.sh
set s2ID $spawn_id

expect -i $s1ID "question1" {
    send_user "exp: question1\n"
    send -i $s2ID "question1\r"
    expect -i $s2ID "answer1" {
        send_user "exp: answer1\n"
        send -i $s1ID "answer1\r"
    }
}
interact

正在运行的 ./auto_s1_s2.exp 的输出为:

s1: started
question1
exp: question1
question1
s2: started
got question1
answer1
exp: answer1

我希望 s1 回显 question1 ,并针对 expect $ s1ID"question1" 进行验证,然后期望脚本将发送 question1 s2 并期望从中得到 answer1 ,然后将 answer 发送到 s1 ,依此类推

I am expecting that s1 echoes question1 which is verify against expect $s1ID "question1" then the expect script would send question1 to s2 and expects answer1 from it then it sends answer to s1 and so on

script1

我在做什么错了?

推荐答案

下面是一个完整的示例.

Here's a full example.

[STEP 101] $ cat s1.sh
echo "s1: started"
echo "question1"
read
echo "got ${REPLY}"
echo "question2"
read
echo "got ${REPLY}"
echo "question3"
read
echo "got ${REPLY}"
echo "s1: finished"
[STEP 102] $ cat s2.sh
echo "s2: started"
read
echo "got ${REPLY}"
echo "answer1"
read
echo "got ${REPLY}"
echo "answer2"
read
echo "got ${REPLY}"
echo "answer3"
echo "s2: finished"
[STEP 103] $

预期部分:

[STEP 104] $ cat qa.exp
spawn bash s1.sh
set s1 $spawn_id

spawn bash s2.sh
set s2 $spawn_id

expect -i $s1 "s1: started"
expect -i $s2 "s2: started"

expect {
    -i $s1 -re "(question.)" {
        set q $expect_out(1,string)

        send -i $s2 "$q\r"
        expect -i $s2 -re "got\[^\r\n]+\[\r\n]+"
        expect -i $s2 -re "(\[^\r\n]+)\[\r\n]+$"
        set a $expect_out(1,string)

        send -i $s1 "$a\r"

        exp_continue
    }
    -i $s1 eof {
        exp_continue
    }
    -i $s2 eof {
    }
}

结果:

[STEP 105] $ expect qa.exp
spawn bash s1.sh
spawn bash s2.sh
s1: started
question1
s2: started
question1
got question1
answer1
answer1
got answer1
question2
question2
got question2
answer2
answer2
got answer2
question3
question3
got question3
answer3
s2: finished
s2: finished
got s2: finished
s1: finished
[STEP 106] $

这篇关于使用Expect自动执行彼此交互的2个脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆