Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create directory if doesn't exists in sftp

Tags:

shell

sftp

I want to create a directory if it doesn't exists after login to sftp server.

test.sh

sftp [email protected] << EOF
mkdir test
put test.xml
bye
EOF

Now i call test.sh and upload different files each time to test folder. When running this

mkdir test

First time it works and second time it throws Couldn't create directory: Failure error?

How to create a directory if doesn't exists and if exists don't create directory in sftp.

like image 536
Galet Avatar asked Dec 11 '14 10:12

Galet


2 Answers

man 1 sftp (from openssh-client package):

-b batchfile

    Batch mode reads a series of commands from an input
    batchfile instead of stdin. Since it lacks user
    interaction it should be used in conjunction with
    non-interactive authentication. A batchfile of ‘-’
    may be used to indicate standard input. sftp will
    abort if any of the following commands fail: get,
    put, reget, reput, rename, ln, rm, mkdir, chdir, ls,
    lchdir, chmod, chown, chgrp, lpwd, df, symlink, and
    lmkdir. Termination on error can be suppressed on a
    command by command basis by prefixing the command
    with a ‘-’ character (for example, -rm /tmp/blah*).

So:

{
  echo -mkdir dir1
  echo -mkdir dir1/dir2
  echo -mkdir dir1/dir2/dir3
} | sftp -b - $user@$host
like image 127
gavenkoa Avatar answered Oct 22 '22 12:10

gavenkoa


I understand this thread is old and has been marked as answered but the answer did not work in my case. The second page on google for a search regarding "sftp checking for directory" so here is an update that would have saved me a few hours.

Using an EOT you cannot capture the error code resulting from the directory not being found. The work around I found was to create a file containing instructions for the call and then capture the result of that automated call.

The example below using sshpass but my script also uses this same method authenticating with sshkeys.

Create the file containing the instructions:

echo "cd $RemoteDir" > check4directory
cat check4directory; echo "bye" >> check4directory

Set permissions:

chmod +x check4directory

Then make the connection using the batch feature:

export SSHPAA=$remote_pass
sshpass -e sftp -v -oBatchMode=no -b check4directory $remote_user@$remote_addy

Lastly check for the error code:

if [ $? -ge "1" ] ; then
  echo -e "The remote directory was not found or the connection failed."
fi

At this point you can exit 1 or initiate some other action. Note that if the SFTP connection fails for another reason like password or the address is incorrect the error will trip the action.

like image 38
DevOps ninja Avatar answered Oct 22 '22 11:10

DevOps ninja