Linux sftp Command: Transfer Files Securely over SSH

sftp is a program that transfers files and manages remote files over an SSH (Secure Shell) connection. The basic connection format is sftp user@host, and it can use SSH host key verification and public key authentication as is.

sftp user@example.com

SFTP is a protocol different from FTP or FTPS, which have similar names. The SFTP subsystem of SSH must be enabled on the server, and it usually uses the same TCP port as SSH.

Features of SFTP and Checks Before Connecting

OpenSSH's sftp performs file transfers over an encrypted SSH connection and can use SSH features such as public key authentication, SSH configuration files, and jump hosts. Full options and interactive commands can be found in the OpenSSH sftp official manual.

  • Server address and SSH port
  • User account to log in
  • Password or SSH private key
  • Trusted path to verify the server host key fingerprint
  • Read and Write Permissions for Remote Directory

Compare the host key fingerprint displayed when first connecting with the value received from the server administrator or a trusted management interface. If you approve it without verification, you could miss a man-in-the-middle attack or connecting to the wrong server.

How to Connect to the Server

Basic Connection

sftp user@example.com

Once connected, the sftp> prompt will appear, allowing you to enter interactive commands. This prompt is for illustration purposes, and only the commands themselves are shown in the code examples below.

Using a Different SSH Port

sftp -P 2222 user@example.com

The port option for SFTP is uppercase -P. Lowercase -p is a different option that requests preservation of modification time, access time, and file permissions, so don’t confuse them.

Specifying a Private Key

sftp -i ~/.ssh/id_ed25519 user@example.com

Restrict permissions for your private key file so that other users cannot read it, and if possible, set a passphrase to use it with an SSH agent. Do not copy your private key to servers or shared directories.

Distinguishing Local and Remote Paths

In SFTP interactive mode, there are separate commands that run on the remote server and on the local computer.

Command Target Description
pwd Remote Displays the current directory of the remote server.
lpwd Local Displays the current directory of the computer on which SFTP is running.
cd path Remote Changes the remote directory.
lcd path Local Changes the local directory.
ls Remote Displays the list of remote files.
lls Local Displays the list of local files.
mkdir Remote Creates a remote directory.
lmkdir Local Creates a local directory.

It is a good habit to check pwd and lpwd before starting work to avoid sending files to the wrong location.

Downloading files

Downloading a single file

get reports/daily.csv

You can specify the local save path as the second argument.

get reports/daily.csv ./download/daily.csv

Downloading multiple files and directories

get reports/*.csv
get -R reports

Wildcards can match remote filenames. When downloading directories recursively, SFTP does not follow symbolic links within the tree, and the support options may vary depending on the server and client versions.

Resuming interrupted downloads

reget archive.tar.zst

Or you can resume partial transfers with get -a. This assumes that the partial local file exactly matches the beginning of the remote file, so if the remote file has changed, the result may be corrupted. For important files, compare checksums after transfer.

Uploading Files

Uploading a Single File

put ./release.tar.zst

You can specify the remote save path or name as the second argument.

put ./release.tar.zst uploads/release.tar.zst

Uploading a Directory Recursively

put -R ./assets uploads/assets

Since existing files can be overwritten, check the remote path first. If it is a directory that multiple users are deploying to simultaneously, it is safer to upload with a temporary name and then use the server-supported atomic rename procedure.

Resuming Interrupted Uploads

reput ./large-image.img

put -a also attempts to resume partial uploads. If the remote partial file does not match the beginning of the local file, a corrupted file may be created, so check for changes and verify the hash after completion.

Handling Paths, Spaces, and Filenames

Enclose paths with spaces in quotes.

get "Monthly Reports/September Report.csv"
put "./Release Files/app package.tar.zst" uploads/

Interactive command interpretation in SFTP is not exactly the same as in a regular shell. For filenames containing wildcards or backslashes, first check the exact name in the list, and for automation, it is safer to use simple and predictable filenames.

Managing connection information with SSH configuration files

Group repetitive options under the Host entry

By writing aliases, users, ports, and key paths in ~/.ssh/config, you can connect briefly.

Host fileserver
    HostName sftp.example.com
    User deploy
    Port 2222
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes
sftp fileserver

Do not put passwords or private key contents into the configuration file. Restrict file permissions and check the priority between system-wide and user configurations.

Connecting via a jump host

sftp -J bastion.example.com user@internal.example.com

-J uses the ProxyJump feature of SSH. Verify the host keys of both the jump host and the target server separately, and only use agent forwarding when necessary.

Automatically Sending in Batch Mode

Creating a Batch File

For example, save the following SFTP commands in upload.sftp.

cd incoming
lcd ./exports
put report.csv report.tmp
rename report.tmp report.csv
bye

Uploading with a temporary name first and then renaming it can reduce the risk of other processes reading an in-progress file as a completed one. Atomicity depends on whether renaming within the same file system on the server is supported.

Running the Batch File

sftp -b upload.sftp fileserver

Batch mode should not rely on user interaction asking for a password. Use a restricted dedicated account and public key authentication, and limit key privileges, access origins, and allowed paths according to the server policy. Do not put passwords in scripts or command lines.

Understanding Failure Handling

In batch mode, if key commands such as get, put, or rename fail, the operation usually stops. You can ignore failures by placing a - before the command, but use this selectively, as it may make the operation appear successful even if necessary files are missing.

In automation, you should check the exit status of the SFTP process, the size of the transferred files, and checksums if possible, and establish notification and retry policies in case of failure.

Security and Operational Checklist

  • Host Key: Verify the fingerprint through a trusted channel during first-time connections and key changes.
  • Authentication: For automation, use a limited-scope public key and a dedicated account instead of passwords.
  • Private Key: Minimize read permissions and do not upload it to storage, backup shared folders, or servers.
  • Path Permissions: Restrict access so the upload account can only reach the necessary directories.
  • Overwrite: Check the target path and existing files, and use temporary names and a version retention policy.
  • Integrity: For important transfers, generate and compare trusted checksums on both sides.
  • Log: Successes and failures of transmissions and their targets are recorded, but passwords, private keys, and contents of sensitive files are not kept.

Comparison of SFTP, SCP, rsync

Tools Suitable situations Features
sftp Interactive file management and standardized transfer Provides remote listing, directory navigation, resume, and batch commands.
scp Simple file copying Easy to copy with a single-line command, but interactive remote management features are limited.
rsync Repeated synchronization and large directories Provides transfer of changed files, exclusion rules, and delete synchronization, but also requires support environment on the server.

Using SSH alone does not automatically make account permissions and deployment procedures secure. Choose based on the purpose of transmission and failure recovery method.

Frequently Asked Questions

Is SFTP FTP with TLS applied?

No. SFTP is the SSH File Transfer Protocol and operates over an SSH connection. FTPS is a separate method that applies TLS to FTP, with different server settings and port structures.

Why does a Connection refused error occur?

The address or port may be incorrect, the SSH service may not be listening, or a firewall may reject the connection. Check the server address, uppercase -P port, SSH service status, and network policies.

What should I do if Permission denied appears?

You need to distinguish whether authentication itself failed or there is insufficient file permission after login. Check connection diagnostic information with sftp -v, but do not share usernames, paths, and server details in public logs.

How do I verify that the upload is complete?

Check the exit status and the size of remote files, and calculate and compare checksums like SHA-256 for important files on both local and remote systems. If the SFTP server uses a restricted account that does not allow arbitrary command execution, a separate verification API or server-side processing procedure may be required.

Summary

After connecting with sftp user@host, use get for downloading and put for uploading. Distinguishing pwd and lpwd, as well as cd and lcd, can help reduce mistakes with remote and local paths.

In operational automation, key points are public key authentication, host key verification, and checking batch exit status and file integrity. Do not store passwords in scripts; limit the transfer range with a dedicated account and minimum privileges.

More in This Category
Linux wget Command: Download Files from URLs

Linux wget Command: Download Files from URLs

Learn how to download Files from URLs with the Linux wget command, including practical examples, key options, and important precautions.

Linux rsync Command: Synchronize Files and Directories

Linux rsync Command: Synchronize Files and Directories

Learn how to synchronize Files and Directories with the Linux rsync command, including practical examples, key options, and important precautions.

Linux printf Command: Print Values with a Defined Format

Linux printf Command: Print Values with a Defined Format

Learn how to print Values with a Defined Format with the Linux printf command, including practical examples, key options, and important precautions.

Linux screen Command: Create and Manage Detachable Terminal Sessions

Linux screen Command: Create and Manage Detachable Terminal Sessions

Learn how to use the Linux screen command to keep terminal sessions running and reconnect to them later, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux dmesg Command: Read Kernel and Boot Messages

Linux dmesg Command: Read Kernel and Boot Messages

Learn how to read Kernel and Boot Messages with the Linux dmesg command, including practical examples, key options, and important precautions.

Linux timedatectl Command: Check Time Zone and Time Synchronization

Linux timedatectl Command: Check Time Zone and Time Synchronization

Learn how to check Time Zone and Time Synchronization with the Linux timedatectl command, including practical examples, key options, and important precautions.

Linux Directory Structure Explained: Purpose of Major Directories

Linux Directory Structure Explained: Purpose of Major Directories

Understand the purpose of major Linux directories such as /etc, /var, /usr, /home, /proc, and /sys, and learn where common system files belong.

Linux last Command: Review Login and Reboot History

Linux last Command: Review Login and Reboot History

Learn how to use the Linux last command to review user login sessions, system reboots, and shutdown history, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux uniq Command: Remove or Count Adjacent Duplicate Lines

Linux uniq Command: Remove or Count Adjacent Duplicate Lines

Learn how to remove or count adjacent duplicate lines with the Linux uniq command, including practical examples, key options, and important precautions.

Linux free Command: Check Memory and Swap Usage

Linux free Command: Check Memory and Swap Usage

Learn how to use the Linux free command to inspect available memory, used memory, cache, and swap usage, with essential options, practical examples, output interpretation, and common troubleshooting tips.