Use sftp to transfer files remotely in Linux

Published: December 18, 2022

Last updated: December 18, 2022

Use sftp to transfer files remotely in Linux

In this article, we cover how to transfer files remotely through SFTP protocol. SFTP (or, SSH File Transfer Protocol) is basically a secure file transfer protocol that helps us with file transfer and management over SSH Protocol.

When compared to now deprecated SCP Protocol, SFTP lets us manage files remotely as well. Furthermore, if the file transfer couldn't happen and there were issues in-between then it would let us resume the transfer later.

We need read and write permissions on the remote as well as local host to make things work while using SFTP. The command-line utility which we will be utilizing also goes by the same name i.e. sftp.

Use SFTP to transfer files remotely

First, open a terminal and use the following syntax that helps connect to remote host -

$ sftp [email protected]

For instance, if the user-name was techpiezo and remote-host at 192.168.1.111

$ sftp [email protected]

This would open a SFTP prompt.

sftp>

I. Now, we can use get command to copy the remote file to local host.

sftp> get /path/to/remote/file /local/host/filename

For instance, if it was file abc.txt at remote host location /home/techpiezo/Downloads. And, we want to copy it as qwerty.txt at local host location - /dev/shm

sftp> get /home/techpiezo/Downloads/abc.txt /dev/shm/qwerty.txt

Then, it would copy abc.txt to location /dev/shm as file - qwerty.txt

If we don't provide local host and filename then, it would copy the file with same filename at the location from where you run SFTP.

If the file was large and got interrupted for some reason. Now, if you wish to resume the transfer then use -a option. Warning: you may corrupt the destination file in case there is a mismatch. So, proceed with caution when resuming files.

sftp> get -a /path/to/remote/file /local/host/filename

We can use -p option to copy both file permissions and access times. Furthermore, if its a directory we want to copy then use -R option to copy it recursively.

II. To transfer the file from local host to remote host then use put command -

sftp> put /path/to/local/file /remote/host/filename

For instance, if we want to transfer test.txt to remote host directory - /dev/shm as  trf-remotefile.txt then,

sftp> put test.txt /dev/shm/trf-remotefile.txt

Options -a, -p and -R can be used to resume file transfer, copy file permissions & access times and recursively copy directories respectively.

In conclusion, we have covered how to transfer files using sftp command-line tool here.