Understanding SFTP Port Usage: Port 22 vs Port 21 in Secure File Transfer Protocol


2 views

SFTP (SSH File Transfer Protocol) operates by default on port 22, not port 21. This is because SFTP runs as a subsystem of SSH (Secure Shell), which uses port 22 by convention. Port 21 is traditionally reserved for FTP (File Transfer Protocol), the unencrypted predecessor to SFTP.

The choice of port 22 is significant because it ensures all file transfers are encrypted through SSH. Unlike FTP which transmits data in plaintext, SFTP provides:

  • End-to-end encryption
  • Secure authentication
  • Data integrity verification

Here's how port 22 is typically specified in different environments:

Linux/Unix sftp command


sftp -P 22 username@hostname

Python Paramiko example


import paramiko

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='username', password='password')
sftp = paramiko.SFTPClient.from_transport(transport)

While port 22 is standard, administrators sometimes change it for security through obscurity. To connect to a non-standard SFTP port:


sftp -P 2222 username@hostname  # Using port 2222 instead of 22

Common port-related problems include:

  • Firewall blocking port 22
  • SSH daemon not running
  • Port conflicts with other services

Verify connectivity using:


telnet hostname 22
# Or with netcat:
nc -zv hostname 22

SFTP (SSH File Transfer Protocol) is often confused with FTP due to similar naming, but they operate differently. Unlike FTP which uses port 21 for control connections, SFTP defaults to port 22 because it runs as a subsystem of SSH (Secure Shell).

SFTP leverages SSH's encryption capabilities, inheriting its default port:

# Typical SFTP connection command (uses port 22 implicitly)
sftp username@hostname

# Explicit port specification (redundant here)
sftp -P 22 username@hostname

While 22 is standard, security considerations might require port changes:

# SSH config file (/etc/ssh/sshd_config) snippet for custom SFTP port
Port 2222
Subsystem sftp /usr/lib/openssh/sftp-server

Then connect using:

sftp -P 2222 username@hostname

Python example using Paramiko for SFTP on non-standard ports:

import paramiko

transport = paramiko.Transport(('hostname', 2222))
transport.connect(username='user', password='pass')
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.listdir('/')  # Example operation

When changing ports:

  • Update firewall rules accordingly
  • Document port changes for team members
  • Consider port knocking for additional security

Common pitfalls include:

# Test SSH connectivity first
ssh -p 22 username@hostname

# Verify SFTP subsystem availability
ssh -p 22 username@hostname sftp