Website Vidya
Linux & ServersStep-by-Step Guide

ftp Command in Linux: Connect & Transfer Files Guide

Learn ftp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
ftp Command in Linux: Connect & Transfer Files Guide
AI Executive SummaryWebsiteVidya AI

10 min read

Learn ftp command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What ftp Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Even in an era dominated by SSH, rsync, and cloud object storage, mastering the ftp command in linux remains a vital skill for interacting with legacy telecommunications equipment, embedded IoT devices, website hosting backends, and public scientific data repositories. Standardized under RFC 959 in 1985, the File Transfer Protocol represents one of the foundational client-server applications of the ARPANET and early Internet.

The command-line ftp client provides an interactive, shell-like environment equipped with dedicated subcommands for authenticating, exploring remote directory hierarchies, toggling data transmission encodings, and transferring single or batch files. While modern public network deployments favor encrypted protocols such as SFTP or FTPS, understanding the operational mechanics of standard FTP is critical for troubleshooting legacy industrial systems and intranet automated file drops.

In this comprehensive guide, we dissect the dual-channel control and data architecture of FTP, examine Active versus Passive connection modes, analyze essential command options, walk through interactive file management examples, and establish secure migration paths.

Advertisement
ftp Command in Linux: Connect & Transfer Files Guide — syntax, flags, and practical terminal workflow diagram
ftp Command in Linux: Connect & Transfer Files Guide — command syntax, key options, and production workflow reference.

What ftp Does and When to Use It

Unlike single-port protocols such as HTTP or SSH, FTP operates over two separate TCP connections: a Control Connection and a Data Connection. When you invoke ftp and connect to a remote host, the client initiates a persistent control connection to TCP port 21 on the server. This channel handles command exchange (e.g., USER, PASS, CWD, RETR, STOR) and server status replies (e.g., 220 Service ready, 230 User logged in, 550 File unavailable) throughout the lifetime of the session.

File transfers and directory listings (ls, dir) require opening a separate dynamic Data Connection. In traditional Active Mode (PORT), the client opens a random unprivileged port and instructs the server to connect back to it from server TCP port 20—a design that routinely fails on modern networks due to client-side NAT routers and firewalls blocking inbound connections. In modern Passive Mode (PASV), the client sends a PASV command, and the server opens an unprivileged dynamic port and provides its IP and port number, allowing the client to initiate the outbound data connection.

At the operating system level, ftp interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running ftp in cloud instances or Kubernetes worker nodes, combining flags such as -p, -v, -n, -i lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The ftp utility is packaged in ftp / inetutils-ftp 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:

Advertisement

Before running administrative tasks or automation scripts, verify whether ftp is installed and inspect which binary path and version your shell resolves:

type -a ftp
ftp --version 2>/dev/null || man -f ftp

# Illustrative output (reviewed against documentation)
ftp is /usr/bin/ftp
ftp (ftp / inetutils-ftp)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y ftp

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y ftp

# Arch Linux
sudo pacman -S --noconfirm inetutils

# Alpine Linux
sudo apk add --no-cache inetutils-ftp

Command Syntax, Arguments, and Exit Status Codes

ftp [-v] [-d] [-i] [-n] [-g] [-p] [host [port]]

The syntax for launching the utility is ftp [-v] [-d] [-i] [-n] [-g] [-p] [host [port]]. Supplying a host immediately connects to the target server; otherwise, ftp opens an interactive ftp> shell where you can initiate connections manually using the open host subcommand. The -p flag forces Passive mode, which is mandatory when operating behind firewalls, cloud security groups, or consumer NAT routers.

Once connected, ftp operates via an internal command language. Key subcommands include binary (or bin) to switch from default ASCII text mode to 8-bit binary mode (preventing file corruption during image, zip, or binary transfers), get and put for single file transfers, mget and mput for multi-file transfers with wildcards, and cd/lcd to navigate remote and local directories simultaneously.

  • 0 — Session completed cleanly and user exited with bye or quit.
  • 1 — Operational failure during connection establishment or command processing.
  • 2 — Invalid command-line option passed during invocation.
  • 130 — Session terminated by user interrupt signal (SIGINT, Ctrl+C).

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-p--passiveForces passive connection mode for data transfers, resolving firewall and NAT connection drops.
-v--verboseEnables verbose mode, displaying all server response codes and data transfer statistics.
-n--no-loginSuppresses automatic login prompting upon initial connection, ideal for scripted automation.
-i--no-promptDisables interactive prompting during multiple file transfers (mget and mput).
-d--debugEnables socket debugging output to inspect low-level FTP protocol control messages.
-g--no-globDisables file name globbing, treating wildcard characters (*, ?) as literal strings.
-A--activeForces traditional active connection mode (client requests server to connect back to client).
-4--ipv4Forces DNS resolution and transport connection strictly over IPv4.
-6--ipv6Forces DNS resolution and transport connection strictly over IPv6.

In unattended shell scripts, combining -n (suppress auto-login) and -i (suppress multi-file confirmation) is standard. This allows scripts to supply authentication credentials via heredocs or ~/.netrc and execute batch transfers without hanging at interactive terminal prompts.

Advertisement

Always verify whether your client defaults to passive or active mode. Most modern Linux distributions configure passive mode by default, but passing -p explicitly guarantees compatibility when scripting across varied Linux and BSD environments.

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 FTP Server in Passive Mode with Verbose Output

Initiate an interactive session to a remote FTP server using passive mode and verbose logging.

ftp -p -v ftp.example.com

# Illustrative output (reviewed against documentation)
Connected to ftp.example.com.
220 (vsFTPd 3.0.5)
Name (ftp.example.com:user): deploy
331 Please specify the password.
Password: 
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

The -p option ensures data connections operate passively, avoiding firewall blocks, while -v prints all 3-digit FTP status codes.

2. Switch to Binary Transfer Mode

Ensure file transfers preserve exact raw byte values without altering newline characters.

ftp> binary

# Illustrative output (reviewed against documentation)
200 Switching to Binary mode.

Binary mode is mandatory for archives, images, PDFs, and compiled executables. The default ASCII mode can corrupt binary files by translating CRLF line endings.

3. Download a Single Remote File with get

Fetch a specific file from the remote working directory and save it locally.

ftp> get server-backup.tar.gz

# Illustrative output (reviewed against documentation)
local: server-backup.tar.gz remote: server-backup.tar.gz
227 Entering Passive Mode (192,0,2,10,195,80).
150 Opening BINARY mode data connection for server-backup.tar.gz (45210080 bytes).
226 Transfer complete.
45210080 bytes received in 1.82 secs (24.2 MB/s)

The get command downloads server-backup.tar.gz to your local working directory, printing transfer throughput statistics upon completion.

4. Upload a Local File to the Remote Server with put

Send a local configuration or data file to the current remote directory.

ftp> put app-release.zip

# Illustrative output (reviewed against documentation)
local: app-release.zip remote: app-release.zip
227 Entering Passive Mode (192,0,2,10,195,81).
150 Ok to send data.
226 Transfer complete.
12450800 bytes sent in 0.54 secs (22.5 MB/s)

The put command streams app-release.zip over the passive data connection and confirms successful delivery with server reply 226.

5. Download Multiple Files Using Wildcards with mget

Download all log files ending in .log without prompting for confirmation on each file.

ftp> prompt
Interactive mode off.
ftp> mget *.log

# Illustrative output (reviewed against documentation)
200 Type set to I.
local: app.log remote: app.log
226 Transfer complete.
local: error.log remote: error.log
226 Transfer complete.

Typing prompt toggles interactive confirmation off, enabling mget *.log to download all matching files sequentially without pausing.

6. Navigate Remote and Local Directories Simultaneously

Use cd to change remote directories and lcd to change local client directories without leaving the ftp shell.

ftp> pwd
257 "/home/deploy" is the current directory
ftp> cd /var/backups
250 Directory successfully changed.
ftp> lcd /tmp/downloads
Local directory now /tmp/downloads

The cd command alters the working path on the remote server, while lcd (local cd) changes the directory on your local workstation.

Real-World Workflows, Pipelines, and Shell Automation

Non-Interactive Automated FTP Upload Script Using Heredoc

Automate daily report uploads in cron scripts by embedding FTP subcommands in a bash heredoc with credentials.

#!/usr/bin/env bash
set -euo pipefail

HOST="ftp.internal.example.com"
USER="automation"
PASS="SecretVaultToken123"
FILE="/var/reports/daily-sales.csv"

ftp -n -v -p "$HOST" <<EOF
user $USER $PASS
binary
cd /incoming
put $FILE
bye
EOF
echo "[SUCCESS] Daily sales report uploaded."

# Illustrative output (reviewed against documentation)
Connected to ftp.internal.example.com.
230 User logged in.
200 Switching to Binary mode.
250 Directory successfully changed.
226 Transfer complete.
221 Goodbye.
[SUCCESS] Daily sales report uploaded.

Using ftp -n suppresses automatic login prompts, allowing the script to pass user credentials and transfer instructions directly via standard input.

Secure Migration Pipeline: Upgrading Legacy FTP to SFTP or LFTP

Migrate automated plaintext FTP file transfers to encrypted SFTP using OpenSSH or lftp with explicit TLS.

# Plain FTP replacement with secure SFTP batch command:
sftp -b - [email protected] <<EOF
cd /incoming
put /var/reports/daily-sales.csv
bye
EOF

# Or LFTP with FTPS (FTP over explicit TLS):
lftp -e "set ftp:ssl-force true; put /var/reports/daily-sales.csv; bye" -u user,pass ftps.example.com

# Illustrative output (reviewed against documentation)
Connected to sftp.example.com.
sftp> cd /incoming
sftp> put /var/reports/daily-sales.csv
Uploading /var/reports/daily-sales.csv to /incoming/daily-sales.csv

Replacing unencrypted FTP with SFTP runs all transfers through encrypted SSH channels (port 22), eliminating cleartext password exposure.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding ftp 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

Standard FTP offers no confidentiality or integrity protection. Authentication credentials, session tokens, and data files travel across the wire in cleartext, making them trivial to intercept via packet sniffing or ARP spoofing on shared networks. In compliance-regulated environments (PCI-DSS, HIPAA, GDPR), standard FTP is explicitly forbidden on public networks.

If automated scripts must store FTP passwords locally, they typically rely on the ~/.netrc file. To prevent local privilege escalation and credential theft, ~/.netrc must be owned strictly by the user with octal permissions set to 600 (chmod 600 ~/.netrc); ftp will refuse to read .netrc if it is readable by other accounts.

GNU/Linux, BSD, and BusyBox Implementation Differences

The classic ftp command in Linux is provided by netkit-ftp or GNU inetutils-ftp. On modern Ubuntu and Debian systems, it is installed via the ftp package, whereas RHEL, Rocky, and Fedora install it via ftp or inetutils.

Due to FTP's age and limitations, modern Linux administrators often prefer more capable clients such as lftp or ncftp, which support TLS encryption (FTPS), automatic resuming, multi-threaded downloads, and robust background queuing.

Troubleshooting Common Errors and Diagnostics

FTP connection hangs indefinitely on LIST or RETR

Root Cause: The client is attempting Active mode, and a client-side NAT router or firewall is dropping incoming connections from server port 20.

Resolution: Force passive mode by passing the -p flag when launching ftp, or execute passive inside the ftp shell.

ftp -p ftp.example.com
# Or inside shell:
ftp> passive

530 Login incorrect or User cannot log in

Root Cause: Invalid username or password, or the user account is listed in /etc/ftpusers on the server (which forbids root or system accounts from logging in via FTP).

Resolution: Verify user credentials and ensure the account is not restricted by server-side vsftpd/proftpd security configurations.

# Test credentials manually:
ftp -v ftp.example.com

550 Permission denied or Read-only file system

Root Cause: The authenticated remote user does not have filesystem write permissions to the target directory, or SELinux boolean ftpd_full_access is disabled on RHEL/CentOS.

Resolution: Verify directory ownership on the server with ls -ld and verify SELinux ftpd booleans.

sudo chmod 775 /srv/ftp/incoming
sudo setsebool -P ftpd_full_access on

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
In Active FTP, the client initiates the control connection to port 21, but the server initiates the data connection back to a client-specified port from port 20. In Passive FTP, the client initiates both the control connection and the data connection to an ephemeral port provided by the server, which works seamlessly through firewalls and NAT routers.
By default, FTP may operate in ASCII mode, which translates newline characters between Unix (LF) and Windows (CRLF) formats. If you download binary files (such as tarballs, images, or zip archives) in ASCII mode, byte alterations will corrupt the file. Always issue the binary command before transferring non-text files.
Create a ~/.netrc file containing 'machine ftp.example.com login myuser password mypass' and set its permissions to chmod 600 ~/.netrc. When you run ftp ftp.example.com, the client automatically reads the credentials and logs in.
Standard FTP is unencrypted. FTPS is FTP wrapped in TLS/SSL encryption for privacy. SFTP (SSH File Transfer Protocol) is an entirely different protocol that runs over OpenSSH on port 22, providing strong public-key authentication, encryption, and firewall simplicity with a single port.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout