2011-04-20 49 views
2

我在bash中使用expect。我想我的脚本telnet到一个盒子,期待一个提示,发送一个命令。如果现在有不同的提示,则必须继续,否则必须再次发送该命令。 我的脚本是这样的:while while loops within expected

\#!bin/bash 
//I am filling up IP and PORT1 here 
expect -c "  
set timeout -1 
spawn telnet $IP $PORT1 
sleep 1 
send \"\r\" 
send \"\r\" 
set temp 1 
while($temp == 1){  
expect { 
Prompt1 { send \"command\" } 
Prompt2 {send \"Yes\"; set done 0} 
} 
} 
" 

输出:

invalid command name "while(" 
    while executing 
"while(== 1){" 

请帮助我。
我试图将其更改为while [ $temp == 1] {

我仍面临以下错误:

输出:

invalid command name "==" 
    while executing 
"== 1" 
    invoked from within 
"while [ == 1] { 
expect { 
+0

你可能想先写一个纯粹的期望脚本在调试这个问题,所以您不必shell引用规则可能会以微妙的方式改变您期望的脚本。 – 2011-04-20 22:37:19

+0

奇怪的错误发生了什么:因为脚本是双引号的,shell(不期望)用'null'替换'$ temp'。 – 2011-04-21 01:23:58

回答

10

这就是我想实现这一点:

expect -c ' 
    set timeout -1 
    spawn telnet [lindex $argv 0] [lindex $argv 1] 
    send "\r" 
    send "\r" 
    expect { 
    Prompt1 { 
     send "command" 
     exp_continue 
    } 
    Prompt2 { 
     send "Yes\r" 
    } 
    } 
} 
' $IP $PORT1 
  • 使用一个q围绕期望脚本来保护预期变量
  • 将shell变量作为参数传递给脚本。
  • 使用“exp_continue”循环,而不是一个明确的while循环(你有反正错终止变量名)
+0

它的工作!谢谢大家!!但有一个查询,当我们把exp_continue,它会发送“命令”,如果它没有看到提示2?我的意思是循环。或者发送一次命令并持续等待prompt2? – Pkp 2011-04-21 00:17:05

+0

当它看到Prompt1时,它会发送命令,然后回到expect块的顶部并等待Prompt1或Prompt2。当它看到提示2时,它发送“是”并刚刚脱离该块。 – 2011-04-21 01:22:02

+0

终于明白了..谢谢:) – Pkp 2011-04-21 01:54:01

4

的,而语法“而人体试验”。每个部件之间必须有一个spce,这就是为什么你会得到错误“没有这样的命令,同时)”

另外,由于tcl引用规则,99.99%的测试需要花在大括号中。因此,语法是:

while {$temp == 1} { 

欲了解更多信息,请参阅http://tcl.tk/man/tcl8.5/TclCmd/while.htm

(你可能有与您选择的壳报价等问题;这个答案解决有关while语句您的具体问题)