Search code examples
bashexpect

if then logic inside expect script


I have an expect script I use for ssh. Some of my hosts prompt with the RSA host key text and some do not. How can I setup my script for an if/then in expect. Here is what I have so far.

#!/usr/bin/expect -f

set ipaddress [lindex $argv 0];
spawn ssh user@$ipaddress
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes\r"
expect "user@$ipaddress's password:"
send "password\r"
set prompt {\$ $}
expect -re $prompt
send "$command\r"
expect -re $prompt
send "quit\r"
interact

The part I need to build in the if/then logic are these two lines:

expect "Are you sure you want to continue connecting (yes/no)?"
send "yes\r"

The logic flow would be:

if expect "Are you sure you want to continue connecting (yes/no)?"
then send "yes\r"
else
expect "user@$ipaddress's password:"
etc..

How can I accomplish this?


Solution

  • This is working for me with the following code modifications.

    expect {
        "Are you sure you want to continue connecting (yes/no)?" {
             send "yes\r"
             exp_continue
        }
        "user@$ipaddress's password:" {
             send "password\r"
        }
        }