RDX
RDX

Reputation: 155

Avoid the timeout in expect programming

Currently we have written a login method using expect programming. There it expects the password and if there is a timeout then it errors out. We have written the following code for that in tcl:

    expect {
        -i $var -re ".*(yes/no)." {
            send -i  $var "yes\r"
            expect {
                -i $var -re ".*pass" {
                    send -i  $var "$pwd\r"
                }
                timeout {
                    puts "Check IP and Password ...timed out"
                    return 0
                }
            }
        }
        -i $var -re ".*pass" {
            send -i  $var "$pwd\r"
            expect {
                -i $var -re ".*Permission denied" {
                    exp_continue
                }
                -i $var -re "Permission denied" {
                    puts "login not succesful - Check IP and Password"
                    return 0
                }
            }
        }
        timeout {
            puts "login  not succesful, Check IP and Password ... timed out"
            return 0
        }
    puts "Connection established."

Now we are observing the code is waiting for the timeout period to get over even if the login is successful, as a result it is consuming some time.

So can anyone suggest how to return the success as soon as the login happens instead of waiting for the timeout to expire?

Upvotes: 0

Views: 122

Answers (1)

Dinesh
Dinesh

Reputation: 16428

With exp_continue, we can just handle this in a easy manner.

set prompt "#|>|\\\$"; # Some commonly used prompts
# We escaped dollar symbol with backslashes, to treat it as literal dollar
expect {
        -i $var 
        timeout {puts "Timeout happened"; return 0}
        "(yes/no)" {send -i  $var "yes\r";exp_continue}
        -re ".*pass" {send -i  $var "$pwd\r";exp_continue}
        "Permission denied" {puts "Permission denied";return 0;}
        -re $prompt {puts "Login successful!!!";return 1}
}

Upvotes: 1

Related Questions