Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loops within expect

I am using expect within bash. I want my script to telnet into a box, expect a prompt, send a command. If there is a different prompt now, it has to proceed or else it has to send that command again. My script goes like this:

\#!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}  
}  
}  
"  

Output:

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

Kindly help me.
I tried to change it to while [ $temp == 1] {

I am still facing the error below:

Output:

invalid command name "=="  
    while executing  
"== 1"  
    invoked from within  
"while [  == 1] {  
expect {
like image 278
Pkp Avatar asked Apr 20 '11 21:04

Pkp


People also ask

How do you use loop in Expect script?

Expect For Loop Examples: for {initialization} {conditions} {incrementation or decrementation} { ... } Expect for loop example : for {set i 1} {$i < $no} {incr i 1} { set $total [expr $total * $i ] } puts "$total"; Note: You should place the loop open brace in the same line as it contains “for” keyword.

What is Exp_continue in Expect?

The command exp_continue allows expect itself to continue executing rather than returning as it normally would. By default exp_continue resets the timeout timer. The -continue_timer flag prevents timer from being restarted. (See expect for more information.)

What is \r in Expect?

\r is carriage return, Ctrl-M or character 015. In an interactive unix context, when you're typing them (or simulating typing them, as with expect), they are interchangeable.

What is Interact in Expect?

Interact is an Expect command which gives control of the current process to the user, so that keystrokes are sent to the current process, and the stdout and stderr of the current process are returned.


1 Answers

This is how I'd implement this:

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
  • use single quotes around the expect script to protect expect variables
  • pass the shell variables as arguments to the script.
  • use "exp_continue" to loop instead of an explicit while loop (you had the wrong terminating variable name anyway)
like image 126
glenn jackman Avatar answered Sep 27 '22 16:09

glenn jackman