Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sftp

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?

like image 365
Adon Smith Avatar asked Dec 24 '22 23:12

Adon Smith


2 Answers

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)

like image 120
Martin Prikryl Avatar answered Apr 29 '23 09:04

Martin Prikryl


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)

like image 42
Julien Kronegg Avatar answered Apr 29 '23 09:04

Julien Kronegg