How To Use SFTP to Securely Transfer Files with a Remote Server

By Justin Ellingwood

How to Connect with SFTP

By default, SFTP uses the SSH protocol to authenticate and establish a secure connection. Because of this, the same authentication methods are available that are present in SSH.

Although passwords are easy to use and set up by default, we recommend you create SSH keys and transfer your public key to any system that you need to access. This is much more secure and can save you time in the long run.

If you can connect to the machine using SSH, then you have completed all of the necessary requirements necessary to use SFTP to manage files. Test SSH access with the following command:

ssh username@your_server_ip_or_hostname

If that works, exit back out by typing:

exit

We can establish an SSH connection and then open up an SFTP session using that connection by issuing the following command:

sftp username@your_server_ip_or_hostname

You will connect the the remote system and your prompt will change to an SFTP prompt.

If you are working on a custom SSH port (not the default port 22), then you can open an SFTP session as follows:

sftp -oPort=custom_port username@your_server_ip_or_hostname

Transferring Files with SFTP

Navigating the remote and local filesystems is of limited usefulness without being able to transfer files between the two.

Transferring Remote Files to the Local System

If we would like download files from our remote host, we can do so by issuing the following command:

get remoteFile
Fetching /home/demouser/remoteFile to remoteFile
/home/demouser/remoteFile                       100%   37KB  36.8KB/s   00:01

As you can see, by default, the “get” command downloads a remote file to a file with the same name on the local file system.

We can copy the remote file to a different name by specifying the name afterwards:

get remoteFile localFile

The “get” command also takes some option flags. For instance, we can copy a directory and all of its contents by specifying the recursive option:

get -r someDirectory

We can tell SFTP to maintain the appropriate permissions and access times by using the “-P” or “-p” flag:

get -Pr someDirectory

Transferring Local Files to the Remote System

Transferring files to the remote system is just as easily accomplished by using the appropriately named “put” command:

put localFile
Uploading localFile to /home/demouser/localFile
localFile                                     100% 7607     7.4KB/s   00:00

The same flags that work with “get” apply to “put”. So to copy an entire local directory, you can issue:

put -r localDirectory

If you receive an error, create the destination directory on the remote end first.