-1

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" 
    }
}


jacobcan118
  • 7,797
  • 12
  • 50
  • 95

1 Answers1

0

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.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • So what is the main reason is cause my script failed? – jacobcan118 May 15 '22 at 18:24
  • Do you know which branch(es) of the expect statement your code followed? I suspect that 1) you sent the password, then 2) in the next loop iteration, expect matched none of those patterns, so it timed out, then 3) in the next loop iteration, the ssh connection had ended, so the spawn_id became invalid. – glenn jackman May 16 '22 at 12:37