sftp command in Linux
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.
sftp provides this functionality. Think of it as an encrypted version of ftp.
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.
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.
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.
-1 | Specify the use of protocol version 1, which dates back to 1997. This option provides compatibility with very old servers. If you're not sure that you need it, do not specify this option. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-2 | Specify the use of protocol version 2, which dates back to 1997. This option provides compatibility with very old servers. If you're not sure that you need it, do not specify this option. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-4 | Forces sftp to use IPv4 addresses only. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-6 | Forces sftp to use IPv6 addresses only. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-B buffer_size | Specify the size of the buffer that sftp uses when transferring files. Larger buffers require fewer round trips, but require more memory to do so. The default is 32768 bytes. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-b batchfile | Batch mode reads a series of commands from an input batchfile instead of stdin. Since it lacks user interaction it should be used in conjunction with non-interactive authentication. If batchfile is specified as a dash ("-"), standard input will be read for the batch of commands. sftp will abort if any of the following commands fail: get, put, rename, ln, rm, mkdir, chdir, ls, lchdir, chmod, chown, chgrp, lpwd, df, symlink, and lmkdir. Termination on error can be suppressed on a command by command basis by prefixing the command with a "-" character (for example, -rm /tmp/file*). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-C | Enables compression (via ssh's -C flag). | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-c cipher | Selects the cipher to use for encrypting the data transfers. This option is directly passed to ssh. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-D sftp_server_path | Connect directly to a local sftp server (rather than via ssh). This option may be useful in debugging the client and server. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-F ssh_config | Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-i identity_file | Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-l limit | Limits the used bandwidth, specified in Kbit/s. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-o ssh_option | Can pass options to ssh in the format used in ssh_config. This is useful for specifying options for which there is no separate sftp command-line flag. For example, to specify an alternate port use: sftp -oPort=24.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-P port | Specifies the port to connect to on the remote host. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-p | Preserves modification times, access times, and modes from the original files transferred. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-q | Quiet mode: disables the progress meter and warning and diagnostic messages from ssh. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-R num_requests | Specify how many requests may be outstanding at any one time. Increasing this may slightly improve file transfer speed but increases memory usage. The default is 64 outstanding requests. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-r | Recursively copy entire directories when uploading and downloading. Note that sftp does not follow symbolic links encountered in the tree traversal. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-S program | Name of the program to use for the encrypted connection. The program must understand ssh options. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-s subsystem | sftp_server | Specifies the SSH2 subsystem or the path for an sftp server on the remote host. A path is useful for using sftp over protocol version 1, or when the remote sshd does not have an sftp subsystem configured. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-v | Raise logging level. This option is also passed to ssh. |
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
bye | Close the session and quit sftp. Same as "exit". | ||||||||||||||||||
cd path | Change the remote working directory to path. | ||||||||||||||||||
chgrp grp path | Change group of file path to grp. path may contain wildcard characters and may match multiple files. grp must be a numeric GID (group ID). |
||||||||||||||||||
chmod mode path | Change the permissions of file path to mode. path may contain wildcard characters and can match multiple files. |
||||||||||||||||||
chown own path | Change owner of file path to own. path may contain wildcard characters and may match multiple files. own must be a numeric UID (user ID). |
||||||||||||||||||
df [-hi] [path] | Display usage information for the filesystem holding the current directory (or path if specified). If the -h flag is specified, the capacity information will be displayed using "human-readable" suffixes. The -i flag requests display of inode information in addition to capacity information. This command is only supported on servers that implement the "[email protected]" extension. | ||||||||||||||||||
exit | Close the session and quit sftp. Same as "bye". | ||||||||||||||||||
get [-Ppr] remote-path [local-path] | Retrieve the remote-path and store it on the local machine. If the local path name is not specified, it is given the same name it has on the remote machine. remote-path may contain wildcard characters and may matcal-path is specified, then local-path must specify a directory. If either the -P or -p flag is specified, then full file permissions and access times are copied too. If the -r flag is specified then directories are copied recursively. Note that sftp does not follow symbolic links when performing recursive transfers. |
||||||||||||||||||
help | Display a help message. | ||||||||||||||||||
lcd path | Change the local working directory to path. | ||||||||||||||||||
lls [ls-options [path]] | Display a directory listing of the local directory path, or the local working directory if path is not specified. ls-options may contain any flags supported by the local system's ls command. path may contain wildcard characters and may match multiple files. |
||||||||||||||||||
lmkdir path | Create a directory on your local system specified by path. | ||||||||||||||||||
ln [-s] oldpath newpath | Create a link from oldpath to newpath. If the -s flag is specified the created link is a symbolic link, otherwise it is a hard link. | ||||||||||||||||||
lpwd | Print the name of the local working directory. | ||||||||||||||||||
ls [-1afhlnrSt] [path] | Display a remote directory listing of either path or the current directory if path is not specified. path may contain wildcard characters and can match multiple files. The following flags alter the behaviour of ls:
|
||||||||||||||||||
lumask umask | Set local umask to umask. | ||||||||||||||||||
mkdir path | Create a directory on the remote system specified by path. | ||||||||||||||||||
progress | Toggle the display of a progress meter. | ||||||||||||||||||
put [-Ppr] local-path [remote-path] | Upload local-path and store it on the remote machine. If the remote path name is not specified, it is given the same name it has on the local machine. local-path may contain wildcard characters and may match multiple files. If it does, and remote-path is specified, then remote-path must specify a directory. If either the -P or -p flag is specified, then full file permissions and access times are copied too. If the -r flag is specified then directories are copied recursively. Note that sftp does not follow symbolic links when performing recursive transfers. |
||||||||||||||||||
pwd | Display the name of the remote working directory. | ||||||||||||||||||
quit | Quit sftp. | ||||||||||||||||||
rename oldpath newpath | Rename a remote file from oldpath to newpath. | ||||||||||||||||||
rm path | Delete the remote file specified by path. | ||||||||||||||||||
rmdir path | Remove the remote directory specified by path. | ||||||||||||||||||
symlink oldpath newpath | Create a symbolic link to oldpath named newpath. | ||||||||||||||||||
version | Display the sftp protocol version. | ||||||||||||||||||
!command | Execute the command command in a local shell. | ||||||||||||||||||
! | Drop into a local shell. Type exit to return to the sftp session. | ||||||||||||||||||
? | Same as "help". |
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).
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. 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.
The output from ssh-keygen looks something like this:
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 username@crunch 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:
chmod 700 ~/.ssh
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:
mkdir ~/.ssh
chmod 700 ~/.ssh
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 myuser@myhostname
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.
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:
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.
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>
sftp [email protected]
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 [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.
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.
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.
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.
Related commands
ftp — Conduct an interactive FTP session over a secure network connection.
slogin — Login to a remote system securely.