0

I have written a code snippet in TCL expect to connect from Server 1 to Server 2 using ssh. Users already may have set passwordless communication between Server 1 and Server 2, or it may ask for a password. Code should handle all these three below possible scenarios:

  1. If passwordless login is enabled between Server 1 and Server 2
  2. No Passwordless login is enabled, Password: prompt is displayed
  3. If user enters incorrect Password, a second Password: prompt is expected where ctrl+c will be entered and will exit.

Please find below the code

#!/usr/bin/expect -f
lassign $argv 1 2 
spawn ssh -o StrictHostKeyChecking=no $1@$2

expect {
      "*]#" { send -- "sleep 0\n" }  #Prompt when passwordless is active and user have logged in
      "Password: " {send -- "$2\n"   #Password prompt when no passwordless is active.
             exp_continue }
      "Password: " {send -- "^C" }   # Second Password Prompt when the wrong password is entered 
                                       in previous step. From here code should exit with a message
       }
 expect "*]#"                # After SSH is successful

I am not able to handle the second Password: prompt for an incorrect password where the code should exit with an appropriate message to the user. I am running the script ./testssh.exp username password.

1 Answer 1

0

Perhaps:

set count 0
expect {
    "Password:" {
        if {[incr count] == 2} {
            # this is the 2nd time, send Ctrl+C
            send -- \x3
            expect eof
            error "incorrect password"
        } else {
            send -- "$2\r"
            exp_continue
        }
    }
    "$prompt"
}
# successfully logged in.
send -- something 
...
1
  • Unfortunately it navigated to # successfully logged in. send -- something block even after wrong password
    – newuser
    Commented Apr 29, 2020 at 9:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .