bash 如何使用带有可选提示的expect?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17621050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:54:52  来源:igfitidea点击:

How to use expect with optional prompts?

linuxbashexpect

提问by joshualan

Let's say I am trying to write an expect script for a test.sh that has three prompts: prompt1, prompt2, prompt3.

假设我正在尝试为具有三个提示的 test.sh 编写一个期望脚本:prompt1、prompt2、prompt3。

My code is like this:

我的代码是这样的:

spawn test.sh
expect "prompt1"
send "pass1"
expect "prompt2"
send "pass2"
expect "prompt3"
send "pass3"

However, prompt2 only occurs half the time. If prompt2 doesn't show up, the expect script breaks. How would I write expect code that skips over prompt2 if it doesn't show up?

但是, prompt2 只出现一半的时间。如果 prompt2 没有出现,expect 脚本就会中断。如果没有出现,我将如何编写跳过 prompt2 的期望代码?

EDIT:

编辑:

Fixed my code:

修复了我的代码:

/usr/bin/expect -c '
spawn ./test.sh
expect {
      "prompt1" {
          send "pass1\r"
          exp_continue
      }
      "prompt2" {
          send "pass2\r"
          exp_continue
      }
      "prompt3" {
          send "pass3\r"
          exp_continue
      }
}
interact return
'

This way, the rest of the script executes and provides output.

这样,脚本的其余部分就会执行并提供输出。

采纳答案by that other guy

You can expect multiple things:

你可以期待很多事情:

expect { 
    "prompt2" { 
        send "pass2"
        expect "prompt3"
        send "pass3"
    }
    "prompt3" {
        send "pass3"
    }
}

回答by jbtule

As long as you have a case that will be always be expected to hit and don't include an exp_continuein that case, you can can remove duplication and handle optional prompts easily:

只要您有一个总是会命中的exp_continue案例并且在这种情况下不包含一个,您就可以删除重复并轻松处理可选提示:

expect "prompt1"
send "pass1"
expect { 
    "prompt2" { 
        send "pass2"
        exp_continue
    }
    "prompt3" {
        send "pass3"
    }
}