简体   繁体   English

在Bash中使用'expect'以及任何顺序的响应

[英]Use 'expect' in Bash with responses in any order

I'm using this expect file (keygen.exp) to generate SSH key, I'm using ssh-keygen just as example to test 'expect': 我正在使用这个期望文件(keygen.exp)来生成SSH密钥,我正在使用ssh-keygen作为测试'expect'的示例:

#!/usr/bin/expect
spawn ssh-keygen

expect "Enter file"
send "./id_rsa\r"

expect "Enter passphrase"
send "\r"

expect "Enter same passphrase"
send "\r"

interact

It works perfectly, however, what if the order of the prompts for inputs is not the same every run, and there might be different questions on different runs ? 然而, 如果每次运行的输入提示顺序不一样,并且在不同的运行中可能会有不同的问题那么它的工作原理会很好吗?

I want something like this: 我想要这样的东西:

#!/usr/bin/expect
spawn ssh-keygen

expect if-is "Enter file"
send "./id_rsa\r"

expect if-is "Enter passphrase"
send "\r"

expect if-is "Enter same passphrase"
send "\r"

interact

Is it possible? 可能吗?

You can have single expect statement which loops, processing different outputs differently, something like: 您可以使用单个expect语句循环,以不同方式处理不同的输出,例如:

expect {
  "Enter file" {
    send "./id_rsa\r"
    exp_continue
  }
  "Enter passphrase" {
    send "\r"
    exp_continue
  }
  "Enter same passphrase" {
    send "\r"
    exp_continue
  }
  $ 
}

But note that you need some way to break out of the loop. 但请注意,你需要一些方法来摆脱循环。 The last pattern here - $ has no exp_continue (or any other action) so it will break out of the loop if the prompt you get when logged in includes $ . 这里的最后一个模式 - $没有exp_continue (或任何其他操作),因此如果登录时获得的提示包含$ ,它将突破循环。 See the full documentation at https://www.tcl.tk/man/expect5.31/expect.1.html 请参阅https://www.tcl.tk/man/expect5.31/expect.1.html上的完整文档

Expect in any order, with infinite timeout: 期待任何顺序,无限超时:

#!/usr/bin/expect
spawn /path/to/some-programme

expect {
  "some string" {
    set timeout -1
    send "some input\r"
    exp_continue
  }
  "some other string" {
    set timeout -1
    send "some other input\r"
    exp_continue
  }
  ...
}

#no 'interact'
#end of file

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

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