简体   繁体   English

如何使用expect和可选提示?

[英]How to use expect with optional prompts?

Let's say I am trying to write an expect script for a test.sh that has three prompts: prompt1, prompt2, prompt3. 假设我正在尝试为test.sh编写一个expect脚本,它有三个提示: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. 但是,prompt2只出现一半的时间。 If prompt2 doesn't show up, the expect script breaks. 如果prompt2没有显示,则expect脚本会中断。 How would I write expect code that skips over prompt2 if it doesn't show up? 如果没有显示,我如何编写跳过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. 这样,脚本的其余部分执行并提供输出。

You can expect multiple things: 你可以期待多种事情:

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

As long as you have a case that will be always be expected to hit and don't include an exp_continue in that case, you can can remove duplication and handle optional prompts easily: 只要你有一个总是会被命中的exp_continue在这种情况下不包括exp_continue ,你可以轻松删除重复并处理可选提示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM