expect script + how to ignore strings if not appears

user1121951 picture user1121951 · Jan 11, 2012 · Viewed 16.8k times · Source

I write the following expect script in order to automate ssh login to remote Linux machine And run the command "cat /etc/APP_VERSION.txt file"

Sometime I not asked from ssh command about-

    "Are you sure you want to continue connecting (yes/no)?"

So in this case the first expect still wait for the string "(yes/no)?" -:(

And not continue to the second expect - "password:" ?

How to resolve this? ,

I mean if the line "Are you sure you want to continue connecting (yes/no)?" Isn’t appears from ssh

Then we must go to the next expect "password:" , but how to do this?

remark1 - in case the question "Are you sure you want to continue connecting (yes/no)?" , Appears then the expect script work fine without any problem .

remark2 - I can’t use timeout positive value (as timeout 10) because ssh itself have delay

. . . .

My expect script: (this expect is part of my ksh script)

  .
  .
  .

  APP_MACHINE=172.12.6.190  


  set timeout -1
  spawn  ssh $APP_MACHINE  
       expect {
                "(Are you sure you want to continue connecting yes/no)?" 
                              { send "yes\r" }
              }
       expect password:        {send PASS123\r}
     expect >  {send "cat /etc/APP_VERSION.txt\r"}
   expect >    {send exit\r}
  expect eof

 .
 .
 .

. . . . .

example of ssh from my linux machine

  ssh APP_MACHINE
  The authenticity of host 'APP_MACHINE (172.12.6.190 )' can't be established.
  RSA key fingerprint is 1e:8a:3d:b3:e2:8c:f6:d6:1b:16:65:64:23:95:19:7b.
  Are you sure you want to continue connecting (yes/no)?

Answer

Kristofer picture Kristofer · Jan 11, 2012

Set a timeout

set timeout 10

Will wait for the expected line for 10 seconds, and then move on to the next line in the script if not received within the specified timeout.

Reference http://linuxshellaccount.blogspot.com/2008/01/taking-look-at-expect-on-linux-and-unix.html

UPDATE: If a timeout is not an acceptable solution you could try using a list of alternative responses to drive the script forward.

expect {
 "(Are you sure you want to continue connecting yes/no)?" { send "yes\r"; exp_continue }
 password:                                                {send PASS123\r; exp_continue}
}