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

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

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?


2 Answers 2


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

spawn ssh user@domain
expect_before "*(yes/no)?" {
    send "yes\r"
expect "*# "

try this:



#!/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"
  "*#" {

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.