Expect script - while loop to validate user input and allow to re-enter while persisting session.

380 Views Asked by At

Please improvise this code, Thanks. I have the following login script, that allows user to 1) loin into the server, then 2) login into the env (QA or DEV or PROD), then 3) using the "suuser" - from user input, finally allows user to login into the App host. Here in my expect script the last 2 lines of code uses $suuser to login into the App host, I wanted to allow user to try 5 times and if unsuccessful I still want to continue current session as currently user at 2nd step being logged in to the env.

expect -c '
puts -nonewline "please enter a swithch user:  "
flush stdout
set suuser [gets stdin]
set userAcc "$env(unixID)";
set userPass "$env(unixPass)";
puts "'$1' '$2'";
spawn ssh $userAcc@'$1'
expect {
    "(yes/no)? " { 
    send "yes\r"
    expect "*assword:*" { send "$userPass\r" }
    }
    "*assword:*" { send "$userPass\r" }
}
expect "*bash*" { send "ssh $userAcc@'$2'\r" }
expect {
    "(yes/no)? " { 
    send "yes\r"
    expect "*assword:*" { send "$userPass\r" }

    set count 5;
    while {$count > 0 } {
    puts "count : $count\n";
    if { [string compare $suuser ""] == 0 } {
        puts -nonewline "please enter a swithch user:  "
        flush stdout
        set suuser [gets stdin]  
        puts $suuser 
    }
    set count [expr $count-1];
    }
    expect -re "*bash*" { send "sudo -u $suuser -i\r" }
    #expect "*$suuser*" {send "$userPass\r" }
       }
}
interact
'
0

There are 0 best solutions below