How to check whether the sftp script is successful??

hi,

how can i check whether the sftp connectivity is successful or not??
i am using expect script to connect to sftp..

sftp_script

spawn /usr/bin/sftp abc@ftp.xyz.com
expect "abc@ftp.xyz.com's password:"
send "password\r"
expect "sftp>"
send "mput *.txt\r"
expect "sftp>"
send "bye\r"
expect eof

i am calling this sftp script from a shell script and checking the return code for 0.

calling_sftp.sh

/home/sftp/sftp_script

RC=$?
if [ $RC -eq 0 ]; then
   echo "successful"
else
   echo "failed"
fi

---------- Post updated at 03:41 PM ---------- Previous update was at 03:11 PM ----------

the sftp script gave this error

send: spawn id exp4 not open
    while executing
"send "mput *.txt\r""
    (file "/home/sftp/sftp_script" line 5)^M

You should not be injecting insecure plaintext passwords into sftp with the expect brute-forcing tool. sftp allows you to use keys, which will make your life much, much simpler, since you can script it directly, run it and wait, instead of having to micromanage every line it prints and reads. Also far more secure, since your scripts will not need to contain your password in plaintext anymore!

hope it helps but put your ssh keys to server as @Corona688 mentioned.

sftp $SFTP_USER@$SERVER <<EOF | grep -q 'No such file'
cd $SFTP_RDIR
ls $SFTP_RFILE
bye 
EOF
if [ $? -eq 1 ] ; then
  echo 'no such remote file'
else
sftp $SFTP_USER@$SERVER <<EOF 
cd $SFTP_RDIR
get $SFTP_RFILE
bye 
EOF
 
fi

The | grep -q 'No such file' might be useless because the error likely goes to stderr, while the pipe reads from stdout.
You need some additional file descriptor magic such as
2>&1 | grep ... (merge stderr with stdout) or
2>&1 >/dev/null | grep ... (merge stderr with stdout then suppress stdout, i.e. capture only stderr).
Further the exit status is reverse: if grep finds something (an error), the exit status is zero!
The following runs directly on the get stuff, lets grep print an error,
and adds an "okay" otherwise.

sftp $SFTP_USER@$SERVER <<EOF 2>&1 | grep 'No such file'
cd $SFTP_RDIR
get $SFTP_RFILE
bye 
EOF
if [ $? -eq 1 ]; then
  # grep did not find an error
  echo "okay"
fi

is there any way to use ftp also without hardcoding the password in the script? currently i am using the below script for ftp

ftp -n remote_server << FTP
  quote USER user
  quote PASS passwrd
  ls -l
  bye
FTP

@Little : try looking at the man page for netrc you can use this to set your ftp credentials

For SFTP?

but inside .netrc file, we have to store the machine name and password in plane text which can be read by anyone.. then how is it secure??

You were storing them anyway. But can it be read by anyone? You don't have to let it be.

chmod 600 ~/.netrc

Now only your user, and root, can read it.