6

I have created a directory within an SFTP location and I want to move a file from one SFTP directory to another directory but cp command is not supported there.

How can I achieve this?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Adon Smith
  • 1,849
  • 7
  • 19
  • 19

2 Answers2

13

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).

The most widespread SFTP server, the OpenSSH supports related copy-data only in very recent version 9.0. Its sftp client has now cp/copy command.


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)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
1

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:myPassword@myftp.mydomain.com
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)

Julien Kronegg
  • 4,968
  • 1
  • 47
  • 60
  • 3
    Few notes: You confuse FTP and SFTP. You are connecting to an SFTP server, not FTP. And you are actually not using the SFTP for the copy. You are invoking a shell command `cp` for the copy (using the [WinSCP command `call`](https://winscp.net/eng/docs/scriptcommand_call)). So actually your solution has nothing to do with SFTP (nor FTP) - In my answer this apporach is covered by the *"If you have SSH/terminal access into the server, use shell `cp` command."* – Martin Prikryl Oct 11 '16 at 09:43
  • @MartinPrikryl : you're right, I was using the FTP term in a confusing way and edited the answer accordingly. BTW thanks for WinSCP, that's a great tool. – Julien Kronegg Oct 11 '16 at 12:22