'issues with spawn id <idx> not open when executing script from iTerm2

I am trying to write a script and execute under iTerm2 profile. However whenever I open the new tab i run into this error. but I execute the same script on Terminal and no problem for it. anyone may know why?

expect: spawn id exp6 not open
`while { 1 } {
(file "xxxxx" line xx)
....

#!/usr/bin/expect

set username [lindex $argv 1]
set hostname [lindex $argv 2]
set password "abcd"
set timeout 60

# trap SIGWINCH and pass to spawned process
trap {
 set rows [stty rows]
 set cols [stty columns]
 stty rows $rows columns $cols < $spawn_out(slave,name)
} WINCH

spawn ssh -o NoHostAuthenticationForLocalhost=yes -o UseKeychain=yes $username@$hostname
while { 1 } {
    expect  "Are you sure you want to continue connecting (yes/no)" {
        send "yes\r"
    } "Enter passphrase for key " {
        interact
        break
    } "password:" {
        send "$password\r" 
    }
}




Solution 1:[1]

To expect several things simultaneously, don't use while use exp_continue

expect  {
    "Are you sure you want to continue connecting (yes/no)" {
        send "yes\r"
        exp_continue
    }
    "Enter passphrase for key " {
        interact
    }
    "password:" {
        send "$password\r"
        interact 
    }
}
  • If you get the connection prompt, send yes and loop back to the expect statement.
  • If you get prompted for the passphrase, just drop into interactive mode.
  • If it's the password prompt, send the password prompt and go interactive.

When the user disconnects, interact will return, the expect statement returns, and the script exits.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 glenn jackman