How to Automate Telnet Session Using Expect

expect script to automate telnet login

My bad.
The problem was with the curly braces. They are supposed to be at the same line as the expect command .

expect - telnet connection

You have a statement here

spawn telnet -l cli $IP

that specifies the username as cli for the telnet session. So the code to login as admin will never be reached.

The default shell prompt for admin is

'# '

The default shell prompt for cli is

'$ '

change your code to handle looking for either shell prompt.

Using expect script inside started telnet session

You are piping the output of expect into telnet; there is no way for expect to receive information back from the telnet process in this scenario.

I would approach this as a chain of expect scripts instead - write one which starts the session, then hands over control to your existing script.

Automating telnet session using bash scripts

Write an expect script.

Here is an example:

#!/usr/bin/expect

#If it all goes pear shaped the script will timeout after 20 seconds.
set timeout 20
#First argument is assigned to the variable name
set name [lindex $argv 0]
#Second argument is assigned to the variable user
set user [lindex $argv 1]
#Third argument is assigned to the variable password
set password [lindex $argv 2]
#This spawns the telnet program and connects it to the variable name
spawn telnet $name
#The script expects login
expect "login:"
#The script sends the user variable
send "$user "
#The script expects Password
expect "Password:"
#The script sends the password variable
send "$password "
#This hands control of the keyboard over to you (Nice expect feature!)
interact

To run:

./myscript.expect name user password


Related Topics



Leave a reply



Submit