title: expect error handling - spawn id not open
body: <p>I'm writing an expect script which can log out in hundreds of routers and change their config.</p>
  
  <p>My problem is, there is a bug on the routers firmware which causes them to close the connection after the password is send.
  If I log in again, it works perfectly (so only the first log in after reboot causes the exception).
  When the connection is closed the expect script is terminated.</p>
  
  <p>I would like if i could gracefully catch the exception, and try again.</p>
  
  <p>The code which fails is this part:</p>
  
  <pre><code># go through each IP
  for {set i $start} {$i &lt;= $end} {incr i} {
    set ip "10.$octet2.$i.x"
  
    puts "\n\n\n#### doing $ip...\n" ; flush stdout
  
    # log in to the IP
    spawn ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -l $user $ip
    expect {
      "continue connecting (yes/no)?" { send "yes\r" ; exp_continue }
      "login as: " { send "$user\r" ; exp_continue }
      "Password: " { send "$pwd\r" }
      "No route to host" { continue }
      timeout { continue }
      }
  
    # execute commands from file
    foreach c "$commands" { eval $c }
  
    }
  </code></pre>
  
  <p>The error I get looks like this:</p>
  
  <pre><code>Password:
  Connection to 10.x.x.x closed by remote host.
  Connection to 10.x.x.x closed.
  send: spawn id exp11 not open
      while executing
  "send "exit\r""
      ("eval" body line 1)
      invoked from within
  "eval $c "
      ("foreach" body line 1)
      invoked from within
  "foreach c "$commands" { eval $c }"
      ("for" body line 18)
      invoked from within
  "for {set i $start} {$i &lt;= $end} {incr i} {
    set ip "10.$octet2.$i.x"
  
    puts "\n\n\n#### doing $ip...\n" ; flush stdout
  
    # log in to the IP
    spa..."
      (file "./multido.exp" line 39)
  </code></pre>
  
  <p>Any help is really appreciated! </p>