5

I have the follow expect script which adds a known host if a known host does not exist.

#!/usr/bin/expect
spawn ssh user@domain "cd /home/user"
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes\r"
interact

The script works fine the first time I ssh into a device however if I ssh into a device for a nth + 1 time, it throws an error

send: spawn id exp6 not open
    while executing
"send "yes\r""
    (file "./testing_spawn.sh" line 4)

presumably because it continues to expect the string Are you sure you want to continue connecting (yes/no)?

How can I tell the script to just interact if that message does not show up?

1
2

Use expect_before to match the "unknown host" question only if it comes before the command prompt:

#!/usr/bin/expect
spawn ssh user@domain
expect_before "*(yes/no)?" {
    send "yes\r"
}
expect "*# "
interact
0

try this:

#./test.exp 1.1.1.1

test.exp

#!/usr/bin/expect -f
set ip [lindex $argv 0]

spawn ssh -q $ip
expect {
  timeout { send_user "\nFailed\n"; exit 1 }
  eof { send_user "\nSSH failure for $ip\n"; exit 1 }
  "Password:" {
    send "password\n"
  }
  "*(yes/no)?*" {
    send "yes\n"
    interact
  }
  "*#" {
    interact
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.