Autologin Expect scripts for telnet/ssh


Tired of typing over and over  your username/password when using telnet/ssh ? Here are Expect https://core.tcl-lang.org/expect/index scripts to autologin by Telnet and ssh.

Note:

  • Yes, it is not secure to keep you username/password saved somewhere, so know what you do . In my opinion  as long as this is a dedicated for remote logins server, that has no access from outside, and hardened accordingly (pertinent to the scripts - only owner/root can read user's home folder, etc.,) the risk is acceptable.

Note 2: password is saved in a file named "sword"

#!/usr/local/bin/expect   Change to the location of your Expect package
 
proc Usage {} {
  puts "\n tel <equipment to enter> \n"
  return
            }
 

set  argnumber  [llength $argv]
 
if {$argnumber==0} {
      puts "You need to specify at least one piece of equipment to log into\n"
      Usage
      exit
 
   }  elseif {$argnumber>1}  {
       puts "You specified too many arguments, only one please\n"
 
      Usage
       exit
                  }
 
set hostName [lindex $argv 0]
 
 puts "Entering $hostName"
 set username "myusername"
 set HANDL [open "sword"]
 set password [gets $HANDL]
 close $HANDL
 spawn telnet $hostName
 expect {[Uu]sername\*} {
  send "$username\r"
 }
 
 expect {[Pp]assword:} {
 send "$password\r"
 }
 

#Cisco specific block - to enter enable level, you may remove this block if not needed
 expect {*#}  {
 send "enable\r"  }
 
 expect {[Pp]assword:} {
 send "$password\r"
 }
 #End of Cisco specific block

 interact

Now SSH login script:

    #!/usr/local/bin/expect   Change to the location of your Expect package
     
    proc Usage {} {
      puts "\n essh  <equipment to enter> \n"
      return
                }
     

    set  argnumber  [llength $argv]
     
    if {$argnumber==0} {
          puts "You need to specify at least one piece of equipment to log into\n"
          Usage
          exit
     
       }  elseif {$argnumber>1}  {
           puts "You specified too many arguments, only one please\n"
     
          Usage
           exit
                      }
     
    set hostName [lindex $argv 0]
     
     puts "Entering $hostName"
     set username "myusername"
     set HANDL [open "sword"]
     set password [gets $HANDL]
     spawn ssh $hostName
     
     expect {[Pp]assword:} {
     send "$password\r"
     }

    #Again goes Cisco - specific block , remove if not needed
     expect {\*#}  {
     send "enable\r"  }
     
     expect {[Pp]assword:} {
     send "$password\r"
     }
     #End of Cisco - specific block

     interact

Follow me on https://www.linkedin.com/in/yurislobodyanyuk/ not to miss what I publish on Linkedin, Github, blog, and more.