如何在没有长脚本的情况下对重复案例使用expect?

时间:2017-11-03 12:10:25

标签: bash shell expect

我正在使用期望运行一个bash脚本,其中ssh为5个盒子,运行aptitude dist-upgrade -d,拉上包,然后将它们scra回原始盒子。

所有方框都有相同的密码,所有方框都需要输入“y”才能对dist-upgrade说“是”。

我目前期望的剧本很长而且很乱,有大量的以下重复

## Original box
expect "password"
send "Password\n"
## Box sshing to
expect "password"
send "Password\n"
expect "want to continue?"
send "y\n"

我的问题是,我如何“重复”这一点,以便在密码被要求的地方发送密码,并且在要求继续提示的地方,它发送y。因此,我不必得到将要发生的事情的完美顺序(有时候,我必须发送“是”的混合密钥检查)

以下完整脚本:

#!/usr/bin/expect -f
set timeout -1
## This uses manualpatching.sh, used to zip up a list of the latest Debian packages
spawn ./manualpatching.sh
## BOX1
expect "password"
send "Password\n"
expect "want to continue?"
send "y\n"
## BOX2
expect "password"
send "Password\n"
expect "password"
send "Password\n"
expect "want to continue?"
send "y\n"
expect "password"
send "Password\n"
expect "connecting"
send "yes\n"
## BOX3
expect "password"
send "Password\n"
expect "password"
send "Password\n"
expect "want to continue?"
send "y\n"
expect "password"
send "Password\n"
## BOX4
expect "password"
send "Password\n"
expect "password"
send "Password\n"
expect "want to continue?"
send "y\n"
expect "password"
send "Password\n"
## BOX5
expect "password"
send "Password\n"
expect "password"
send "Password\n"
expect "want to continue?"
send "y\n"
expect "password"
send "Password\n"
## BOX6
expect "password"
send "Password\n"
expect "password"
send "Password\n"
expect "want to continue?"
send "y\n"
expect "password"
send "Password\n"
## END
expect eof

1 个答案:

答案 0 :(得分:3)

感谢Gaurav指出我正确的方向。

我使用exp_continue缩小了我的脚本,现在它更干净,更通用:

#!/usr/bin/expect -f
set timeout -1
spawn ./manualpatching.sh
expect {
      "Are you sure you want to continue connecting (yes/no)" {
            send "yes\r"
            exp_continue
      }
      "password" {
            send "Password\r"
            exp_continue
      }
      "want to continue?" {
            send "y\r"
            exp_continue
      }
}