Search code examples
bashexpect

Bash/Expect Time-Out on Password returns 0


I have a bash script which contains the following snippet:

function test_sftp_connection() {
expect << EOF
log_user 0
spawn -noecho sftp -P $SFTP_SERVER_PORTNUMBER $SFTP_SERVER_USERNAME@$SFTP_SERVER_HOSTNAME
expect "password:"
send "$SFTP_SERVER_PASSWORD\r"
expect "sftp>"
send "exit\r"
EOF

  # Check the exit status of the expect command
  if [ $? -ne 0 ]; then
    echo "Unable to connect to the SFTP server."
    exit 1
  fi
}

My current understanding is that 'expect "sftp>"' does what it says it does; it expects an sftp> prompt. So if a wrong password was entered by the script, and you are asked to enter the password again; this is obviously not the same. So I expect it to stop executing; returning with a non-zero status code.

Unfortunately, it does not do this. Instead, it times out with status code 0. I don't understand why it does this or how I can solve this. It would be much appreciated if someone knows how to deal with this situation.


Solution

  • I've changed log_user 0 to log_user 1 to enable logging of output and I added an additional expect block to handle the case when the prompt is not sftp>,so in this case I exit with a status code of 1 using the timeout keyword!

    check this out :

    function test_sftp_connection() {
      expect << EOF > /dev/null
      log_user 0
      spawn -noecho sftp -P $SFTP_SERVER_PORTNUMBER $SFTP_SERVER_USERNAME@$SFTP_SERVER_HOSTNAME
      expect "password:"
      send "$SFTP_SERVER_PASSWORD\r"
      expect {
        "sftp>" {
          send "exit\r"
          expect eof
          exit 0
        }
        timeout {
          exit 1
        }
      }
    EOF
    
      if [ $? -ne 0 ]; then
        echo "Unable to connect to the SFTP server."
        exit 1
      fi
    }