How do I tell expect that I have finished the interactive mode?

Pkp picture Pkp · Apr 9, 2011 · Viewed 12.8k times · Source

I am writing some expect commands in bash.

Script:

#!/bin/bash  
set timeout -1  

expect -c "  

spawn telnet $IP $PORT1  
sleep 1  
send \"\r\"  
send \"\r\"  
expect Prompt1>  
interact timeout 20 {  
sleep 1  
}  

expect {  
Prompt2> {send \"dir\r\" }  
}    

"  

My intentions with the script are, first let it telnet into a machine, when it sees Prompt1, let it give control to me, I will execute a command to load a specific image. Then wait until Prompt2 shows up (which indicates image has been loaded). Then Let it execute the further set of commands.

After running the script, I could get into the interactive mode, load my image. The problem is getting out of interactive mode on the remote machine and giving back control to it.

The Error which I got:

expect: spawn id exp4 not open  
    while executing  
"expect -nobrace Prompt2 {send "dir\r" }"  
    invoked from within  
"expect {    
Prompt2 {send "dir\r" }  
}"  

How can I do this?

Answer

Mike Pennington picture Mike Pennington · Apr 9, 2011

Your problem is two-fold...

  1. You should interact with an explicit return, and give it some way to know you've released control... in this case, I use three plus signs and hit enter.

  2. After you return control, the script will need to get the prompt again, which means the first thing you do after returning control to expect is send another \r. I edited for what I think you're trying to do...

Example follows...

#!/bin/bash  
set timeout -1  

expect -c "  

spawn telnet $IP $PORT1  
sleep 1  
send \"\r\"  
send \"\r\"  
expect Prompt1>  
interact +++ return

send \"\r\"
expect {  
Prompt2> {send \"dir\r\" }  
}
"