Expect - Telnet Connection

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.

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 .

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.

Linux expect script sometimes ending with `Connection closed by foreign host`, is this expect script or device issue?

The problem is in here:

send "show hw-inventory details\r"
expect $prompt
send "exit\r"

You set prompt "#" which is very dangerous. The output of show hw-inventory details does have the char # (see the line part# 82.86S-8609-R6 rev C) so expect $prompt would succeed and then it send "exit\r" and so the connection is closed.

Solution: Use a more accurate string for the prompt, for example:

# '[' needs to be backslash escaped or it'll trigger Tcl's command substitution
set prompt "HENKEL_CAPITAL_2-EQU\[>#]"

linux - telnet - script with expect

You can try this way too.

set user_id {}
expect -re {nick=(.*)\s+id=(.*)\s+group=(.*)\s+login=(.*)\n} {
#Each submatch will be saved in the the expect_out buffer with the index of 'n,string' for the 'n'th submatch string
puts "You have entered : $expect_out(0,string)"; #expect_out(0,string) will have the whole expect match string including the newline
puts "Nick : $expect_out(1,string)"
puts "ID : $expect_out(2,string)"
puts "Group : $expect_out(3,string)"
puts "Login : $expect_out(4,string)"
set user_id $expect_out(2,string)
}

send "This is $user_id, reporting Sir! ;)"
#Your further 'expect' statements goes below.

You can customize the regexp as per your wish and note the use of braces {} with -re flag in the expect command.

If you are using braces, Tcl won't do any variable substitution and if you need to use variable in the expect then you should use double quotes and correspondingly you need to escape the backslashes and wildcard operators.



Related Topics



Leave a reply



Submit