On Unix-like operating systems, sftp is the command-line interface for using the SFTP secure file transfer protocol. It is an encrypted version of FTP. It transfers files securely over a network connection.

Description

You may already be familiar with FTP: it’s a very simple, and very insecure method for uploading or downloading files over a network connection. It does not provide any sort of secure encryption in the session or in the data transfer.

  • Description
  • Syntax
  • Examples
  • Interactive command examples
  • Related commands
  • Linux commands help

sftp provides this functionality. Think of it as an encrypted version of ftp.

Syntax

sftp performs all operations over an encrypted ssh session. It uses many of the features of ssh, such as public key authentication and data compression.

If you need to transfer files over anonymous FTP, sftp is not the program to use. Because all sftp connections are encrypted, they require a username and password (or public key authentication). So, for anonymous FTP transfers, use regular ftp.

There are four basic ways to use sftp, and the command syntax for each is listed here. (For more information about each option and it’s possible values, see the Options section, below).

  • The first is an interactive session. In this mode, sftp connects and logs into the specified host, then enters its interactive command mode, where you type all your commands at a prompt. To launch an interactive session of sftp, use the following syntax:sftp [-1246Cpqrv] [-B buffer_size] [-b batchfile] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-R num_requests] [-S program] [-s subsystem | sftp_server] host See Interactive Mode for an example of using sftp this way.
  • You can also use sftp to retrieve files automatically, without any prompted interaction:sftp [user@]host[:file …] See Automatic Retrieval Mode for an example of using sftp in this way.
  • Or you can tell sftp to start its interactive session in a specific remote directory:sftp [user@]host[:dir[/]] See Starting Interactive Mode In A Specific Remote Directory for an example of using sftp this way.
  • Lastly, you can run a completely automated session using the -b option. The “b” stands for “batch mode.” To use batch mode, it is necessary to configure non-interactive authentication, such as public key authentication, so that you don’t have to manually enter a password. The sftp syntax for this mode is:sftp -b batchfile [user@]host For examples of using batch mode, and a guide to setting up public key authentication, see Batch Mode.

Options

Here is a description of each of the options listed in the command syntaxes listed above.

sftp [-1246Cpqrv] [-B buffer_size] [-b batchfile] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-R num_requests] [-S program] [-s subsystem | sftp_server] host

sftp [user@]host[:file …]

sftp [user@]host[:dir[/]]

sftp -b batchfile [user@]host

Interactive mode

In interactive mode, sftp logs you into the remote system and places you at a prompt that is similar to the command prompt on your local system. It offers you a limited, but very useful, set of commands with which you can navigate the remote file system and send and receive files.

Let’s say you want to start an interactive sftp session on the server named “server.myhost.com”. And, let’s say your user account on server.myhost.com is named “user”. From your system’s command line, You can start the session using the command:

sftp [email protected]

Or, if your username on your local system is also “user”, you could type:

sftp server.myhost.com

…and your username “user” automatically sends it as the username.

The server will respond by asking you for your password:

[email protected]’s password:

…and if you enter it correctly, you will receive a “you’re connected” message, and the sftp prompt, like this:

Connected to server.myhost.com. sftp>

You can now move around in the filesystem with “cd directory”, list files with “ls”, download files with “get filename”, and upload files with “put filename”. It’s pretty much identical to an interactive ftp session, except it’s encrypted and secure.

When you’re done, you can log off with the “bye” command (“exit” also works), and sftp will exit.

Here’s a list of the commands you can use in Interactive Mode:

Interactive mode commands

Notes

  • Interactive Mode commands are case-insensitive, so it doesn’t matter if you spell them with capital or lowercase letters (or a mix of both). Filenames are still case-sensitive, however.
  • Any file or directory names that contain spaces must be enclosed in quotes, or the server will interpret them as separate names.

Automatic retrieval mode

In this mode, you can specify the exact pathname of the file (or files) you want to retrieve in the sftp command itself. For example, if you want to get the file documents/portfolio.zip from the remote server files.myhost.com (where your username is myname), you could use the command:

sftp [email protected]:documents/portfolio.zip

When you run this command, sftp will connect to files.myhost.com, ask you for your password, and once you’re authenticated it attempts to download the file documents/portfolio.zip. Since we didn’t put a slash at the beginning of the directory name, it looks for documents in your home directory on the server. If it finds portfolio.zip, it downloads it.

The output looks like this:

Fetching /home/myname/documents/portfolio.zip to portfolio.zip

…and then sftp will exit. You can also specify a location for the file to be downloaded. For instance, this command:

sftp [email protected]:documents/portfolio.zip /tmp

…downloads portfolio.zip into your /tmp directory. Or, you can specify a completely different name for the downloaded file:

sftp [email protected]:documents/portfolio.zip /tmp/portfolio-new.zip

…and the output will indicate the new filename:

Fetching /home/myname/documents/portfolio.zip /tmp/porfolio-new.zip

You can also specify wildcards in the filename, for instance:

sftp [email protected]:documents/*.zip

…and sftp downloads any files with the extension .zip in the documents remote directory. The output lists each file on its own line, like this:

Fetching /home/myname/documents/portfolio.zip to portfolio.zip Fetching /home/myname/documents/resume.zip to resume.zip Fetching /home/myname/documents/profile-pic.zip to profile-pic.zip

Starting interactive mode in a specific remote directory

Sometimes it’s more convenient to start an interactive mode session from a specific remote directory. You can do this by specifying it on the command line:

sftp [email protected]:documents/budget/april/

[email protected]’s password: Connected to files.myhost.com. Changing to: /home/myname/documents/budget/april/ sftp>

Batch mode

It’s also possible to run sftp in a completely scripted fashion. This is called batch mode, and it allows you to perform sftp transfers without any interaction at the keyboard. This is useful, for instance, if you want to set up a recurring transfer in a cron job, or a one-time scheduled transfer using the at command.

However, because batch mode is completely non-interactive, it does not allow you to enter a username and password when connecting to the server. So, to use batch mode, you’ll have to log in automatically. The standard way to do this, and the most secure, is to use public key authentication. Let’s go over that quickly.

Setting Up Public Key Authentication

Public Key Authentication allows you to log into a remote server securely without typing in your password. First, you generate two keys on your local system: a private key and a public key. Then you copy the text of your public key onto the remote server. After that, as long as you have the private key on your local machine, you can log into the remote machine without typing in a password.

To do this, the first step is to generate the public and private keys.

The keys will be located in the directory .ssh in your home directory on your local system. First, check to see if the .ssh directory already exists:

ls -d ~/.ssh

This either returns the directory name:

/home/username/.ssh

…or tell you that it doesn’t exist:

ls: cannot access /home/username/.ssh: No such file or directory

If it doesn’t exist, we need to create it before the next step:

mkdir ~/.ssh

Next, we need to make sure this directory has the correct permissions. Ensure you’re the only person who can access this directory (read, write, and execute). For a directory, the octal value of this file mode is 700. Let’s change the permissions on our .ssh directory:

chmod 700 ~/.ssh

Now we need to generate the keys themselves. The program used to generate key pairs for the ssh protocol is called ssh-keygen. Run it at the command line without any options:

ssh-keygen

Itprompts you for the information it needs to generate the keys. Use all the default values (press Enter at every prompt).

The output from ssh-keygen looks something like this:

One of the prompts asks you for a passphrase, which offers an additional level of security on top of the encrypted private key. Here we will leave the password blank. If you want to use a password with your key, use a program called ssh-agent to load your key into memory; this allows you to use a password-protected key without having to type in the password more than once.

Generating public/private rsa key pair. Enter file in which to save the key (/home/username/.ssh/id_rsa): Created directory ‘/home/username/.ssh’. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification is saved in /home/username/.ssh/id_rsa. Your public key is saved in /home/username/.ssh/id_rsa.pub. The key fingerprint is: d4:7b:66:c4:e6:ba:78:87:e7:23:08:c7:0d:d7:b0:7f [email protected] The key’s randomart image is: +–[ RSA 2048]—-+ | | | … | | . .P+ | | .. o=. | | …S+.e= | | . o .=. E | | o … . | | ..e.+.+ | | …=.. | +—————–+

You’ll even get a neat piece of art representing your public key, which you can print out and hang on your wall, if you like.

Your keys are now generated. There are two files, id_rsa and id_rsa.pub. We need to change the permissions on these files as well, so that no one but you can access them (read, write, and execute). The octal value of these permission bits is 700.

chmod 700 ~/.ssh/id_rsa*

And make sure the directory has the same permission bits set:

Now ssh to your server. Let’s say it’s called myhost.com:

ssh [email protected]

Enter your password and log in. Once you’re at your server’s command prompt, check to see if the .ssh directory exists there. On the server:

ls -d ~/.ssh

If it doesn’t exist, create it, and give it the appropriate permissions, like on your local system. On the server:

Same for the authorized_keys file. First check that it exists. On the server:

ls ~/.ssh/authorized_keys

If it doesn’t, create it. You can use touch to create an empty file. On the server:

touch ~/.ssh/authorized_keys

chmod 700 ~/.ssh/authorized_keys

Of course, if the directory and file exist already, you don’t need to create them. Either way, once you know the ~/.ssh/authorized_keys file exists, you can log out of the server:

logout

Which returns you to your local system command prompt.

Now you need to place the contents of your local public key file (~/.ssh/id_rsa.pub, which you created earlier with ssh-keygen) into the file ~/.ssh/authorized_keys on your server.

The contents of this file are all-in-one very long line (no line breaks). You can look at it yourself with the cat command:

cat ~/.ssh/id_rsa.pub

…and it looks something like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTiP0LXi74qgpp6VBqzro67QOGtum10 t2epYsOm6kKncf62JVMSlwYH7QwAskxkA6ripvo+TlwRBqqLaF2ACX4CivQkoabqsdFAd uGcKVICUFZaexUmw2eIEKF4qCOvRDP/Juol1S+ID1glYJRSqDcmAb3jApTRDMXM/w7Tl3 qz5/cp3MINKM3+apBfe7F7iDezjQ/U0HqtH2+Np83u4X2G+LIFnpV0RdalkqCuM6tSv2C m4FdPazsIwSmFptBKnw00IdIqYpnkQmOJMk47cGDzqczii7KMCy3wRNqkaLwefRB0MZeJ ipz4+a27kQEqerAIHt37/MMT5XNqn3mqbI [email protected]

This line of text needs to be placed into the authorized_keys file on your server, on its own line. There are several ways to do this: you could copy the text on your local server, open the file using a text editor on the server, and paste it in on its own line. Or, you could use a program called ssh-copy-id, which is part of the default ssh installation on many systems. However, here we will append it directly to the file using ssh itself.

If your remote username is myusername and your server name is myhost.com, you would run this command:

cat ~/.ssh/id_rsa.pub | ssh [email protected] ‘cat » ~/.ssh/authorized_keys’

This runs the cat command on your public key file, pipes the output to ssh, which takes that input and appends it directly to the authorized_keys file on the remote machine.

Now your public key is installed on the server, and be able to log in without a password, and conduct batch sftp sessions.

RSAAuthentication yes PubkeyAuthentication yes

These are part of the default configuration, so you don’t need to add them, set them, or un-comment them in the configuration file. However, they are required for public key authentication. If it’s not working, this is the first place, check.

If the server is still asking you for your password when you try to log in, check that the server’s ssh daemon configuration, located by default in /etc/ssh/sshd_config, contains the following two lines:

Executing the batch sftp session

To run a batch sftp session, create a text file containing the sequence of sftp commands to run on the server, with each command on its own line. For instance, if you want to automate the uploading of a set of files called image01.jpg, image02.jpg… into a directory on the remote server called images in your home directory, you could create a text file called mybatch.txt which contains the following commands:

cd images put image*.jpg

Then, you would execute the batch with the following command:

sftp -b mybatch.txt [email protected]

…and sftp outputs the results of the commands, for example:

sftp> cd images sftp> put image*.jpg Uploading image01.jpg to /home/myname/images/image01.jpg Uploading image02.jpg to /home/myname/images/image02.jpg Uploading image03.jpg to /home/myname/images/image03.jpg

After all commands are executed (successfully or not), sftp will log out and return you to the command line.

Examples

sftp myhost.com

This command attempts to initiate an interactive sftp session with the server myhost.com. The name used to log in will be the same as the username with which you ran the command. Once you are successfully logged in, you will see a message similar to the following, along with the sftp> command prompt:

Remote system type is UNIX. Using ASCII mode to transfer files. sftp>

Same as the above command, but attempts to log in with the username fred.

sftp [email protected]:/home/fred/images

Attempts to initiate an interactive sftp session with the server myhost.com, using the name fred to log in. Upon successful login, you begin the session in the directory /home/fred/images.

sftp fre[email protected]:/home/fred/images/picture.jpg

Attempts to download the file /home/fred/images/picture.jpg from the server myhost.com using the username fred to log in. If the file exists, it will be downloaded to the local working directory, and then sftp will exit.

sftp -b batch.txt [email protected]

Attempts to execute the sftp commands in the text file batch.txt, on the server myhost.com, as the user named fred. The commands in the file batch.txt must be listed one per line. For the session to be initiated, the server and local client must be configured so that no keyboard input is required to log in; see Setting Up Public Key Authentication above for more information.

Interactive command examples

The following examples may run from the sftp> prompt once an interactive session is initiated. See Interactive Mode Commands above for a complete list of interactive commands and options.

pwd

Prints the name of the remote working directory.

lpwd

Prints the name of the local working directory.

ls

List the contents of the remote working directory.

lls

List the contents of the local working directory.

cd documents

Changes the remote working directory to the subdirectory documents.

lcd documents

Changes the local working directory to the subdirectory documents.

get mydocs.zip

Download the remote file mydocs.zip into the local working directory.

get mydocs.zip /home/fred

Download the remote file mydocs.zip into the local directory /home/fred. If the directory /home/fred does not exist, sftp will attempt to download the file into the local directory /home and name it fred.

get mydocs.zip /home/fred/downloaded-docs.zip

Download the remote file mydocs.zip into the local directory /home/fred, giving it the new name downloaded-docs.zip after it is downloaded.

sftp does not recognize the tilde shortcut for home directories ("~"), so you have to use the complete name of a home directory if you’re specifying it in sftp.

mkdir documents

Create the directory documents in the remote working directory.

put documents.zip

Upload the local file documents.zip into the remote working directory.

put /home/fred/documents/documents.zip /home/fred/documents/mydoc.zip

Upload the local file /home/fred/documents/documents.zip into the remote directory /home/fred/documents, renaming it mydoc.zip after it is uploaded.

put /home/fred/images/image*.jpg /home/fred/images

Upload all files in the local directory /home/fred/images whose name starts with image, and ends in the suffix .jpg, into the remote directory /home/fred/images.

rename /home/fred/file.txt /home/fred/newfile.txt

Rename the remote file /home/fred/file.txt, giving it the name newfile.txt.

rm /home/fred/newfile.txt

Delete the remote file /home/fred/newfile.txt.

!commandname option1 option2

Run the command commandname option1 option2 on your local system without disconnecting from the sftp session.

bye

Disconnect from the sftp session, and quit sftp.

ftp — Conduct an interactive FTP session over a secure network connection.slogin — Login to a remote system securely.