sftp Command in Linux: Interactive and Automated Secure Transfers
Learn sftp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn sftp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What sftp Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
The sftp command in linux provides a secure, modern replacement for legacy FTP, enabling administrators and automated systems to manage files across remote servers with complete cryptographic protection. Packaged as a standard component of OpenSSH, sftp implements the IETF SSH File Transfer Protocol over an authenticated SSH-2 channel.
The sftp command in Linux (SSH File Transfer Protocol) provides secure, encrypted interactive file transfers and remote filesystem management over an SSH connection. Unlike legacy unencrypted FTP, sftp encrypts all credentials and data payloads over a single SSH port (22), supporting interactive remote navigation, directory management, permission manipulation, and automated batch scripting.
Legacy FTP protocols transmit usernames, passwords, and data payloads across networks in unencrypted plain text. Furthermore, FTP requires separate control and dynamic data ports (passive port ranges), complicating cloud security groups and NAT traversal. In contrast, sftp multiplexes all control commands, directory queries, and data streams through a single encrypted SSH port (default port 22), simplifying firewall management.
sftp operates in two primary modes: an interactive FTP-like shell environment that allows users to navigate remote and local filesystems simultaneously, and a non-interactive batch mode (-b) that automates scripted file exchanges in cron jobs and production data ingestion pipelines.
What sftp Does and When to Use It
At the architectural level, sftp establishes a standard SSH connection and requests the execution of the remote sftp subsystem (specified as Subsystem sftp /usr/lib/openssh/sftp-server in sshd_config). The sftp client communicates with the remote server process through binary Type-Length-Value (TLV) packets multiplexed over SSH Channel 0.
A key architectural advantage of SFTP in production environments is the ability to enforce chroot isolation. By configuring ChrootDirectory and ForceCommand internal-sftp in sshd_config, administrators can jail external partners or automated upload accounts into a specific directory tree. The in-process internal-sftp daemon executes without requiring shell binaries (/bin/sh), shared C libraries, or /dev nodes inside the chroot jail, providing an airtight security sandbox.
At the operating system level, sftp interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running sftp in cloud instances or Kubernetes worker nodes, combining flags such as -P PORT, -i KEY, -b BATCHFILE, -r lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.
Availability and Installation Across Linux Distributions
The sftp utility is packaged in openssh-client across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether sftp is installed and inspect which binary path and version your shell resolves:
type -a sftp
sftp --version 2>/dev/null || man -f sftp
# Illustrative output (reviewed against documentation)
sftp is /usr/bin/sftp
sftp (openssh-client)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y openssh-client
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y openssh-clients
# Arch Linux
sudo pacman -S --noconfirm openssh
# Alpine Linux
sudo apk add --no-cache openssh-client
Command Syntax, Arguments, and Exit Status Codes
sftp [OPTIONS] [user@]host[:path]
The invocation syntax is: sftp [OPTIONS] [user@]host[:path]. Connection options mirror OpenSSH: -P specifies a non-standard SSH port, -i supplies an identity key file, -b batchfile runs automated commands without interactive prompts, and -C enables compression.
Inside the interactive sftp shell, commands divide into remote and local actions. Standard commands operate on the remote server (ls, cd, pwd, mkdir, rm, rmdir). Commands prefixed with an 'l' operate on your local machine (lls, lcd, lpwd, lmkdir). The get command downloads remote files locally, while put uploads local files to the remote server.
0— Successful session termination or batch file completion with no errors.1— Operational failure; authentication error, network disconnect, or batch command failure.255— SSH connection failure; unable to reach host, invalid port, or host key verification rejected.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-P PORT | --port | Specifies the remote port number to connect to (note uppercase -P). |
-i KEY | --identity | Selects the private key file for public key authentication. |
-b BATCHFILE | --batch | Enables non-interactive batch mode, reading commands line-by-line from BATCHFILE. |
-r | --recursive | Recursively uploads or downloads entire directory hierarchies. |
-C | --compress | Enables transparent compression on the SSH transport stream. |
-q | --quiet | Suppresses progress meters and non-error diagnostic messages. |
-v | --verbose | Increases logging verbosity to debug SSH handshake and SFTP packet exchanges. |
-l LIMIT | --limit | Limits transfer bandwidth consumption in Kbit/s. |
-o OPTION | -o | Passes arbitrary OpenSSH client options (e.g., -o StrictHostKeyChecking=no). |
For production automation, combining -b with -o BatchMode=yes is best practice (e.g., sftp -b commands.txt -o BatchMode=yes user@host). The BatchMode=yes option instructs SSH to disable interactive password prompts; if public key authentication fails, sftp aborts immediately rather than hanging an unattended cron script.
Within the interactive shell, remember the local command prefix 'l'. For example, running pwd prints the remote working directory (/var/www), while lpwd prints the local working directory (/home/user). Similarly, ls lists remote files, whereas lls lists local files.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Connect to an Interactive SFTP Session
Establish an encrypted interactive file transfer session to a remote Linux server.
sftp [email protected]
# Illustrative output (reviewed against documentation)
Connected to 192.0.2.10.
sftp>
sftp completes SSH authentication and displays the interactive sftp> prompt, ready to accept file management commands.
2. Connect Using a Custom Port and Identity Key
Authenticate to a remote SFTP service running on port 2222 with an Ed25519 SSH private key.
sftp -P 2222 -i ~/.ssh/partner_key [email protected]
# Illustrative output (reviewed against documentation)
Connected to 192.0.2.10.
sftp>
The uppercase -P specifies port 2222, and -i loads partner_key for passwordless public key authentication.
3. Download a Remote File to the Local Working Directory
Retrieve a remote file and save it locally using the get command.
sftp> get /var/log/app.log ./local_app.log
# Illustrative output (reviewed against documentation)
Fetching /var/log/app.log to ./local_app.log
/var/log/app.log 100% 12MB 14.2MB/s 00:00
The get command transfers /var/log/app.log from the remote server and writes it to ./local_app.log.
4. Upload a Local File to the Remote Server
Transfer a local software package to the remote server using the put command.
sftp> put release.tar.gz /opt/uploads/
# Illustrative output (reviewed against documentation)
Uploading release.tar.gz to /opt/uploads/release.tar.gz
release.tar.gz 100% 45MB 18.5MB/s 00:02
The put command uploads release.tar.gz into the remote /opt/uploads/ directory.
5. Download an Entire Directory Recursively
Retrieve an entire remote directory structure and all nested files using get -r.
sftp> get -r /var/www/uploads/ ./backup_uploads/
# Illustrative output (reviewed against documentation)
Fetching /var/www/uploads/ to ./backup_uploads/
Retrieving /var/www/uploads/file1.jpg
Retrieving /var/www/uploads/file2.png
The -r option instructs get to traverse remote directories recursively, recreating the directory tree locally.
6. Execute Automated Non-Interactive Batch Script
Automate routine file transfers by passing a text file containing sequential SFTP commands via the -b flag.
sftp -b /opt/scripts/sftp_commands.txt [email protected]
# Illustrative output (reviewed against documentation)
sftp> cd /incoming
sftp> put /data/export_*.csv
sftp> bye
sftp executes the commands listed in sftp_commands.txt sequentially without user interaction and exits upon completion.
Real-World Workflows, Pipelines, and Shell Automation
Automated Partner Data Ingestion Pipeline with Batch Scripts
Automate nightly retrieval of partner data feeds, archiving transferred files remotely upon successful download.
#!/usr/bin/env bash
set -euo pipefail
SFTP_HOST="partner.example.com"
SFTP_USER="datafeed"
KEY_FILE="~/.ssh/datafeed_key"
LOCAL_STAGING="/data/partner_ingest"
BATCH_FILE="/tmp/sftp_batch_$$.txt"
mkdir -p "${LOCAL_STAGING}"
# Generate dynamic batch command file
cat << 'EOF' > "${BATCH_FILE}"
cd /outgoing
lcd /data/partner_ingest
mget *.csv
rename *.csv *.processed
bye
EOF
echo "=== Executing Automated SFTP Ingestion ==="
sftp -b "${BATCH_FILE}" -o BatchMode=yes -i "${KEY_FILE}" "${SFTP_USER}@${SFTP_HOST}"
rm -f "${BATCH_FILE}"
echo "Ingestion complete. Transferred files:"
ls -lh "${LOCAL_STAGING}"
# Illustrative output (reviewed against documentation)
=== Executing Automated SFTP Ingestion ===
sftp> cd /outgoing
sftp> lcd /data/partner_ingest
sftp> mget *.csv
Fetching /outgoing/transactions_20261022.csv to transactions_20261022.csv
sftp> bye
Ingestion complete. Transferred files:
-rw-r--r-- 1 admin admin 4.2M Oct 22 21:45 transactions_20261022.csv
This production pipeline dynamically builds an SFTP batch script, runs it in unattended batch mode (-b), and cleans up temporary files upon completion.
Hardened Chroot SFTP Jail Configuration for Third Parties
Configure the OpenSSH server daemon to restrict external upload accounts strictly to an isolated chroot jail without shell access.
# 1. Create dedicated sftponly group and upload user
sudo groupadd sftponly
sudo useradd -g sftponly -d /upload -s /usr/sbin/nologin partner_user
sudo mkdir -p /srv/sftp/partner_user/upload
# 2. Permissions: Chroot root directory MUST be owned by root!
sudo chown root:root /srv/sftp/partner_user
sudo chmod 755 /srv/sftp/partner_user
sudo chown partner_user:sftponly /srv/sftp/partner_user/upload
# 3. Add configuration block to /etc/ssh/sshd_config:
# Match Group sftponly
# ChrootDirectory /srv/sftp/%u
# ForceCommand internal-sftp
# PasswordAuthentication no
# X11Forwarding no
# AllowTcpForwarding no
sudo sshd -t && sudo systemctl reload sshd
echo "Chroot SFTP jail configured successfully."
# Illustrative output (reviewed against documentation)
Chroot SFTP jail configured successfully.
This workflow establishes an isolated SFTP jail where users can transfer files via internal-sftp but cannot spawn shells or browse host files.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding sftp inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
SFTP commands such as rm, rmdir, and put overwrite or delete files immediately without prompting for confirmation. Unlike Git or versioned object storage, deleted files cannot be restored from the SFTP command line.
Unlike FTPS (which wraps traditional FTP in TLS and requires managing dynamic passive port ranges), SFTP operates entirely across a single SSH port (22). This eliminates firewall traversal vulnerabilities and prevents FTP bounce attacks.
A common pitfall with automated SFTP accounts is interactive shell output: if a user's remote ~/.bashrc or /etc/motd prints text messages (such as 'Welcome to the server!'), the banner corrupts binary SFTP protocol handshakes, causing the client to fail with 'Received message too long'. Ensure automated accounts suppress all shell echo messages.
GNU/Linux, BSD, and BusyBox Implementation Differences
The OpenSSH sftp client is standard across Linux, BSD, and macOS distributions, maintaining consistent command syntax. Windows 10/11 also bundles sftp via the native OpenSSH feature.
Third-party graphical SFTP clients (FileZilla, WinSCP, Cyberduck) use the exact same underlying SFTP protocol. When troubleshooting graphical client connectivity, testing the connection via the CLI sftp command quickly verifies whether issues stem from SSH authentication or client-side GUI configuration.
Troubleshooting Common Errors and Diagnostics
Received message too long ... Ensure your remote login scripts don't output anything
Root Cause: The remote account's ~/.bashrc or /etc/profile prints text or banners to standard output, corrupting the binary SFTP protocol handshake.
Resolution: Wrap shell startup output in an interactive check: [ -z "$PS1" ] && return.
# Add to top of remote ~/.bashrc:
[ -z "$PS1" ] && return
fatal: bad ownership or modes for chroot directory
Root Cause: The directory specified in ChrootDirectory is writable by non-root users, violating OpenSSH security requirements.
Resolution: Ensure all parent directories leading to and including the ChrootDirectory are owned by root and not group-writable.
sudo chown root:root /srv/sftp/partner_user
sudo chmod 755 /srv/sftp/partner_user
sftp> put: Permission denied
Root Cause: The authenticated user does not have write permissions to the remote target directory.
Resolution: Check remote directory ownership and permissions with ls -ld /path.
ssh admin@remote-host "sudo chown partner_user:sftponly /upload && sudo chmod 775 /upload"
Alternatives, Related Commands, and Related Tutorials
- Netcat (nc) Command in Linux: Port Scanning, Transfers, and Debugging — Practical syntax, flags, and examples for
nc. - curl Command in Linux: Transfer Data, Test APIs, and HTTP Requests — Practical syntax, flags, and examples for
curl. - How to Use Linux Screen: Manage Persistent Terminal Sessions — Practical syntax, flags, and examples for
screen. - scp Command in Linux: Secure File Transfer Examples and Syntax — Practical syntax, flags, and examples for
scp. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides


Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!