问题
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.
回答1:
You need at least one branch in that expect command that does not "exp_continue": put the pattern for the prompt as the last pattern in the expect command with no action: when expect sees the prompt, the expect command will end and you script can carry on.
expect {
timeout {
puts "Network Connection Problem"
close
exit ;# if you don't exit, your next command is "send" which will fail
}
"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
}
"# "
}
send -s -- "show version\r"
回答2:
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.
来源:https://stackoverflow.com/questions/50567300/expect-telnet-connection