Expect脚本中的'if else'语句

3

我正在尝试创建一个脚本,根据执行前面的脚本后收到的输出,“发送”输入。

#!/usr/bin/expect --
set timeout 60

spawn ssh user@server1

expect "*assword*" { send "password\r"; }

expect "*$*" { send "./jboss.sh status \r"; }
if [ expect "*running*" ];
        then { send "echo running \r"; }
else { send "./jboss.sh start \r"; }
fi

我想做类似这样的事情,但是我卡在了if else语句中。我该如何修复它?
1个回答

4
您可以简单地将它们分组为单个的expect语句,无论哪个匹配,都可以相应地进行处理。
#!/usr/bin/expect
set timeout 60
spawn ssh user@server1
expect "assword" { send "password\r"; }
# We escaped the `$` symbol with backslash to match literal '$' 
# The last '$' sign is to represent end-of-line
set prompt "#|%|>|\\\$ $"
expect {
        "(yes/no)"  {send "yes\r";exp_continue}
        "password:" {send "password\r";exp_continue}
        -re $prompt 
}
send "./jboss.sh status\r"
expect {
        "running" {send "echo running\r"}
        -re $prompt {send "./jboss.sh start \r"}
}
expect -re $prompt

1
这个复合体expect { "(yes/no)" {send "yes\r";exp_continue} "password:" {send "password\r";exp_continue} -re $prompt }非常重要,因为您可以获得多个响应,否则过程基本上是单独的 if语句,并且变得相互独立。这个程序处理第一次连接时出现的“保存RSA密钥”(或其他算法)问题。 另外,如果您在一个循环中执行此操作,请确保 close,否则程序可能会继续 spawning并逃跑,有效地成为了一个 fork bomb - eulerworks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接