Search code examples
expectprompt

User input for Expect script


I am new to scripting. How can I write an Expect script to ssh into a device and prompt the user for password? We use a pin + RSA token code as the password so I can't store the password.

#!/usr/bin/expect -f

spawn ssh device1

Solution

  • I have used this code before to achieve what you wish to achieve. You can take it as a reference point to write your own version of the code.

    #!/usr/bin/env expect -f
    set passw [lindex $argv 0]
    
    #timeout is a predefined variable in expect which by default is set to 10 sec
    set timeout 60 
    spawn ssh $user@machine
    while {1} {
      expect {
    
        eof                          {break}
        "The authenticity of host"   {send "yes\r"}
        "password:"                  {send "$password\r"}
        "*\]"                        {send "exit\r"}
      }
    }
    wait
    #spawn_id is another default variable in expect. 
    #It is good practice to close spawn_id handle created by spawn command
    close $spawn_id
    

    Source: Expect Wiki