'expect script to automate telnet login
I have been trying to create an expect script to automatically login to my device through telnet
If there are no multiple possibilities for the expect command , the script works fine, logs in to the device.
#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set port [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn telnet $ip $port
expect "'^]'." sleep .1;
send "\r";
sleep .1;
expect "login:"
send "$user\r"
expect "Password:"
send "$password\r";
interact
The script above works fine and logs in successfully when i pass the correct parameters. But once i add additional branches(for error handling) to the expect command , the script gets stuck at login: prompt.After some time it prints Script Error
Any help?? Erroneous script below.
#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set port [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]
spawn telnet $ip $port
expect "'^]'."
sleep .1;
send "\r";
expect
{
"login:"
{
send "$user\r"
expect "Password:"
send "$password\r";
interact
}
"host: Connection refused"
{
send_user "ERROR:EXITING!"
exit
}
}
PS: This script is to be further developed to wait for additional prompts to load different build images on the device. Only telnet(console) connection works. so ssh is not an option.
Solution 1:[1]
here is a script using expect to achieve telnet auto login. I just tried and it really works.
#!/usr/bin/expect -f
if {[llength $argv] < 1} {
puts "Usage: ./telnet.sh host";
exit 1;
}
set timeout 10
set host [lindex $argv 0]
set user "my_user"
set password "my_password"
spawn telnet -l $user $host
expect {
"?ser*" {
send "$user\n"
exp_continue
}
"?ogin*" {
send "$user\n"
exp_continue
}
"?assword*" {
send "$password\n"
interact
exit 0;
}
}
exit 1
link: https://www.oueta.com/linux/telnet-auto-login-on-linux-and-unix-with-expect/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zhang zhiqiang |
