title: expect script to automate telnet login
body: <p>I have been trying to create an expect script to automatically login to my device through telnet </p>
  
  <p>If there are no multiple possibilities for the expect command , the script works fine, logs in to the device. </p>
  
  <pre><code>#!/usr/bin/expect
  set timeout 20
  set ip [lindex $argv 0]
  set port [lindex $argv 1]
  set user [lindex $argv 2]
  set password [lindex $argv 3]
  
  spawn telnet $ip $port
  expect "'^]'." sleep .1;
  send "\r";
  sleep .1;
  expect   "login:"
  send "$user\r"
  expect "Password:"
  send "$password\r";
  interact
  </code></pre>
  
  <p>The script above works fine and logs in successfully when i pass the correct parameters. But once i add additional branches(for error handling) to the expect command , the script gets stuck at <code>login:</code> prompt.After some time it prints <a href="http://pastebin.com/n6CX8mtv" rel="noreferrer">Script Error</a>
  Any help?? Erroneous script below.</p>
  
  <pre><code>#!/usr/bin/expect
  set timeout 20
  set ip [lindex $argv 0]
  set port [lindex $argv 1]
  set user [lindex $argv 2]
  set password [lindex $argv 3]
  
  spawn telnet $ip $port
  expect "'^]'."
  sleep .1;
  send "\r";
  expect
  {
    "login:"
    {
          send "$user\r"
          expect "Password:"
          send "$password\r";
          interact
  
    }
  
    "host: Connection refused"
    {
      send_user "ERROR:EXITING!"
      exit
    }
  
  }
  </code></pre>
  
  <p>PS: This script is to be further developed to wait for additional prompts to load different build images on the device. Only telnet(console) connection works. so ssh is not an option.  </p>