首页 > 解决方案 > 期望脚本等待特定输入一段时间

问题描述

我正在通过 docker 安装 Windows 应用程序,这需要一些用户输入,如数据库设置等。我正在使用这些用户输入的期望脚本来自动化我们的安装。

但在最后一步中,我的安装需要 15-20 分钟,因为应用程序需要安装 DB 模式和其他必需元素,然后给出最终输入以按 Enter 键退出安装过程。

我该如何处理它,目前我只是让我的期望脚本等待,但是无论如何我可以处理这个并让期望脚本等待那个特定的输入“字符串匹配”?

这是我的期望脚本的样子

    #!/bin/bash

expect -c '
  spawn sh ./setupapp.sh
  expect "PRESS <ENTER> TO CONTINUE:"
  send "\r"
  expect "PRESS <ENTER> TO CONTINUE:"
  send "\r"
  expect "PRESS <ENTER> TO CONTINUE:"
  send "\r"
  expect "PRESS <ENTER> TO CONTINUE:"
  send "\r"
  expect "PRESS <ENTER> TO CONTINUE:"
  send "\r"
expect "PRESS <ENTER> TO CONTINUE:"
  send "\r"
  expect "Waiting here:"
  send "\r"
  expect "Waiting here:"
  send "\r"
  expect "Waiting here:"
  send "\r"
  expect "Waiting here:"
  send "\r"
  expect "Waiting here:"
  send "\r"
  expect "Waiting here:"
  send "\r"
 expect "PRESS <ENTER> TO Exit Installation:"
 send "\r"
  expect eof
'

我在这里使用 Waiting 等待 10 秒,有什么方法可以自动化并等待最后一个字符串按 Enter 退出安装。

谢谢!

标签: linuxshexpect

解决方案


看起来你想要这样的东西:这是期望某事发生多次的最灵活的方式,我们不必关心它究竟发生了多少次。

expect -c '
  set timeout 1200   ;# 20 minutes
  spawn sh ./setupapp.sh
  expect {
    "PRESS <ENTER> TO CONTINUE:" {
      send "\r"
      exp_continue
    }
    "Waiting here:" {
      send "\r"
      exp_continue
    }
    timeout {
      error "nothing happened after $timeout seconds" 
    }
    "PRESS <ENTER> TO Exit Installation:" {
      send "\r"
    }
  }
  expect eof
'

该期望命令等待四件事之一发生。对于前 2 个,按 Enter 键,然后继续等待另一个事件。我添加了“超时”事件,以防你想在那里做一些特别的事情。

“按回车退出”块不调用“exp_continue”。在它发送回车后,封闭的expect命令结束,然后我们等待eof。


推荐阅读