Search code examples
linuxtclexpecttelnet

expect - telnet connection


I'm trying to create a simple telnet connection script. I spawn telnet process. Depending on the version, it may or may not ask for password.

After that It asks for username and password and rulese acceptation. After successful login it prompts for command.

However, thing I wrote does not work.

#/usr/bin/expect -f
set IP [lindex $argv 0]
set timeout 10
set send_slow {10 .5}
log_user 1

spawn telnet -l cli $IP

expect {
    timeout {
        puts "Network Connection Problem"
        close
    }
    "Password:" {
        send -s -- "cli\r"
        exp_continue
    }
    "Username:" {
        send -s -- "admin\r"
        expect "Password:"
        send -s -- "admin\r"
        exp_continue
    }
    "(Y/N)?" {
        send -s -- "Y\r"
        exp_continue
    }   
}
expect "# "
send -s -- "show version\r"

After running script, I go through login and agreement. Once prompt is shown, script does not execute show version command. Cursor blinks after few seconds I see info:

expect: spawn id exp6 not open while executing "expect "# ""

Can someone please correct my mistakes? I've read expect manual, went through exemplary scripts but could not find any solution. I'm sure it's simple, yet I'm struggling here.

Help me Captain.


Solution

  • 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.