amar2108
amar2108

Reputation: 323

How to check if SFTP session was authenticated successfully

I am trying to SFTP between two servers, currently I have setup the keys for both the servers, but in case if the keys are not setup I want to know the authentication has failed.

The script contains sftp command followed by bunch of other commands in EOF structure, but the session gets stuck in prompt for password and doesn't move forward when the keys are not setup. I have tried grepping for 'password:' after 10 secs and if grep successful then print 'authentication failure', but wasn't able to do this properly.

I tried grepping for password prompt to know that keys are not setup but this script gets stuck on password prompt and doesn't move forward

#/!bin/ksh

FILE=`echo "getme.txt"`

TARGET_IP=`echo "targethost"`
USER=`echo "user01"`

kgen_path=`echo "/pet1usr/ph/pet01/backupssh"`

echo "connecting"

sftp ${USER}@${TARGET_IP} << EOF 2>&1 | grep 'password: '
cd $kgen_path
cd 2019
put $FILE
bye

EOF

if [[ $? -eq 1 ]];
then
  echo "Authentication successful"
else
  echo "Authentication failure"
fi

echo "done"

I tried adding the timeout command too, but there was no prompt for any password and script ended after 10 secs

timeout 10s sftp ${USER}@${TARGET_IP} << EOF 2>&1 | grep 'password: '

This script doesn't work and I'm getting "Authentication Successful" or it is getting stuck in password prompt, Is there some better way to check if authentication was successful or any changes in the code please let me know?

Upvotes: 2

Views: 2022

Answers (2)

RCat
RCat

Reputation: 169

You could use "sftp -vv" to use verbose mode and check all the process.

Upvotes: 0

Cyrus
Cyrus

Reputation: 88583

Disable password prompt:

sftp -o BatchMode=yes user@host

Upvotes: 2

Related Questions