How can I copy/duplicate a file to another directory using SFTP?

Solution 1:

The core SFTP protocol does not support duplicating a remote file.

There's draft of copy-file extension to the protocol. But that's supported by only few SFTP servers (ProFTPD/mod_sftp and Bitvise SFTP server for example) and few SFTP clients (WinSCP for example).

It's definitely not supported by the most widespread OpenSSH SFTP server. Nor by OpenSSH SFTP client (sftp), i.e. there's no cp command or any other functionally equivalent.


Alternatives:

  • If you have SSH/terminal access into the server, use the shell cp command.
  • If your SFTP server supports the copy-file extension, use an SFTP client that supports it too.
  • Otherwise, your only option is to download the file to a local temporary location and upload its copy back to a different/target remote directory.
    Some SFTP clients can do this for you even transparently in one go (e.g. in WinSCP, see Duplicate via local temporary copy option on Duplicate dialog).

(I'm the author of WinSCP)

Solution 2:

You can clone remote directories using WinSCP in command line mode (winscp /console). Let's imagine you have a the following structure on the remote SFTP server:

theDestinationDirectory/
  |-file1.txt
  |-file2.txt

You can copy this remote directory using the following script (in WinSCP console):

open sftp://myUsername:[email protected]
mkdir theDestinationDirectory
call cp theSourceDirectory/* theDestinationDirectory/ -r

Then you can check that your copy has been done properly (in the WinSCP console):

ls theDestinationDirectory

drwxr-sr-x   2 uid12345 gid12345        37 Jul 29 23:50:24 2016 .
drwxr-sr-x   6 uid12345 gid12345        75 Jul 29 23:50:11 2016 ..
-rw-r--r--   1 uid12345 gid12345     29670 Jul 29 23:50:24 2016 file1.txt
-rw-r--r--   1 uid12345 gid12345     12432 Jul 29 23:50:24 2016 file2.txt

Note that as Martin Prikryl wrote, this may not be supported by all SFTP servers... (at least it's supported by mine)