Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Expect/TCL - Handling a Telnet connection failure

Status
Not open for further replies.

bryan3k

Technical User
Oct 6, 2010
4
0
0
US
Hello,

I have an Expect script that logs into a number of routers to perform backups and it works pretty well. The problem I am having is figuring what to do when the host is not responding.

Here is the snippet for the log in procedure:

proc log_in {host} {
global spawn_id
spawn telnet $host
expect "Username:"
send "cisco\r"
expect "Password:"
send "cisco\r"
expect "*>"
send "enable\r"
expect "Password:"
send "cisco\r"
expect "*#"
send "terminal length 0\r"
}

The log_in function is called from this main part of the script:

set routers [open "D:\\Tcl\\mine\\routers-cisco.txt" "r"]

while { [eof $routers] != 1 } {
gets $routers host
log_in $host
backup
verify $host
}

At first I was going to use the expect command to match "connection failed" which well eventually be displayed when the host is down, but that requires me to increase the expect timeout which impacts hosts that do respond as they wait for the "connection failed" match to timeout.

In addition, when I use this method, the log_in function returns to the while loop and tries to perform the backup function which is no longer valid for that host. At that point I would need to read a new host from $routers and proceed to log_in for that host.

Anyone done this before? If you need more info, I can paste the entire script.

Thanks.
 
Ok, I think I came up with a solution. I went ahead with my original plan, but moved the backup and verify functions under the log_in function:

proc log_in {host} {
global spawn_id
spawn telnet $host
exp_internal 1
set timeout 30
expect {
"Connect failed" { fail $host; return }
"Username:" { send "cisco\r" }
}
expect "Password:"
send "cisco\r"
expect "*>"
send "enable\r"
expect "Password:"
send "cisco\r"
expect "*#"
send "terminal length 0\r"
backup
verify $host
}

Now when the host fails to respond, the expect scripts matches "Connect failed", performs the actions in the "fail" function then returns control back to the while loop, which can now read a new value into $host because I have moved the backup and verify functions from the loop.

So far, it's looking good.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top