SSH, SCP, and SFTP - Complete Linux Remote Access Guide

SSH (Secure Shell), SCP (Secure Copy), and SFTP (SSH File Transfer Protocol) are essential tools for secure remote access and file transfer in Linux environments. This comprehensive guide covers everything from basic connections to advanced configurations, security hardening, and troubleshooting. Master these tools to efficiently manage remote systems and transfer files securely.

SSH Family Tools Comparison

Tool Purpose Protocol Use Case Security
SSH Secure remote shell access SSH Protocol Command-line administration High (encrypted)
SCP Secure file copy SSH Protocol Simple file transfers High (encrypted)
SFTP Secure file transfer SSH Protocol Interactive file management High (encrypted)
Rsync over SSH Efficient file synchronization SSH + Rsync Backups, large transfers High (encrypted)
Quick Reference:
• Basic SSH: ssh user@hostname
• SCP file copy: scp file.txt user@hostname:/path/
• SFTP session: sftp user@hostname
• Generate SSH key: ssh-keygen -t ed25519
• Copy SSH key: ssh-copy-id user@hostname
• Check SSH config: ssh -G hostname
• Always use key-based authentication for security
• Test connections before relying on them in scripts

Remote Access Workflow

Secure Remote Access Process

Generate Keys
Configure SSH
Test Connection
Transfer Files
Manage Remote
Secure Access

Essential SSH Configuration Files

Configuration File Location Purpose Security Impact
sshd_config /etc/ssh/sshd_config SSH server configuration High
ssh_config /etc/ssh/ssh_config SSH client configuration Medium
authorized_keys ~/.ssh/authorized_keys Allowed public keys High
known_hosts ~/.ssh/known_hosts Verified host keys Medium
config ~/.ssh/config Client connection settings Low

SSH - Secure Shell

🔑
SSH Authentication

Secure authentication methods and key management.

ssh [options] [user@]hostname [command]

Authentication Methods:

  • ssh user@hostname - Password authentication
  • ssh -i key.pem user@hostname - Key file authentication
  • ssh -o PreferredAuthentications=publickey - Force key auth
  • ssh-copy-id user@hostname - Copy public key to server

Examples:

# Basic connection
ssh username@server.example.com

# Connect with specific port
ssh -p 2222 username@server.example.com

# Connect with identity file
ssh -i ~/.ssh/id_rsa username@server.example.com

# Execute remote command
ssh username@server.example.com 'ls -la'

# X11 forwarding
ssh -X username@server.example.com

# Agent forwarding
ssh -A username@server.example.com

# Verbose output for debugging
ssh -vvv username@server.example.com
⚙️
SSH Key Management

Generate and manage SSH keys for secure authentication.

ssh-keygen, ssh-copy-id, ssh-add

Key Management:

# Generate ED25519 key (recommended)
ssh-keygen -t ed25519 -C "your_email@example.com"

# Generate RSA key (legacy)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# Generate key with specific name
ssh-keygen -t ed25519 -f ~/.ssh/mykey

# Copy public key to server
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server.example.com

# Start SSH agent
eval "$(ssh-agent -s)"

# Add key to agent
ssh-add ~/.ssh/id_ed25519

# List loaded keys
ssh-add -l

# Remove key from agent
ssh-add -d ~/.ssh/id_ed25519
🔧
SSH Configuration

Client and server configuration for optimal performance and security.

~/.ssh/config, /etc/ssh/sshd_config

Client Configuration:

# ~/.ssh/config
Host myserver
    HostName server.example.com
    User username
    Port 22
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60
    ServerAliveCountMax 3

Host *.example.com
    User admin
    Compression yes
    ForwardAgent yes

Host internal*
    User deploy
    ProxyJump bastion.example.com

# Now connect with: ssh myserver

SCP - Secure Copy

📁
Basic File Transfer

Secure file copying between local and remote systems.

scp [options] source target

Basic Operations:

  • scp file.txt user@host:/path/ - Upload file
  • scp user@host:/path/file.txt . - Download file
  • scp -r directory/ user@host:/path/ - Recursive copy
  • scp -P 2222 file.txt user@host:/path/ - Specific port

Examples:

# Copy local file to remote server
scp file.txt username@server.example.com:/home/username/

# Copy remote file to local system
scp username@server.example.com:/path/to/file.txt .

# Copy directory recursively
scp -r directory/ username@server.example.com:/path/

# Copy with specific port
scp -P 2222 file.txt username@server.example.com:/path/

# Copy with identity file
scp -i ~/.ssh/id_rsa file.txt username@server.example.com:/path/

# Preserve file attributes
scp -p file.txt username@server.example.com:/path/

# Limit bandwidth (KB/s)
scp -l 1000 largefile.iso username@server.example.com:/path/
🔄
Advanced SCP Usage

Advanced file transfer scenarios and options.

scp advanced options

Advanced Operations:

# Copy between two remote hosts via local
scp -3 user1@host1:/file.txt user2@host2:/path/

# Use compression for slow connections
scp -C file.txt username@server.example.com:/path/

# Use specific cipher for encryption
scp -c aes256-ctr file.txt username@server.example.com:/path/

# Copy with verbose output
scp -v file.txt username@server.example.com:/path/

# Copy multiple files
scp file1.txt file2.txt file3.txt username@server.example.com:/path/

# Use wildcards (quote properly)
scp "*.log" username@server.example.com:/path/

# Copy with specific SSH options
scp -o ConnectTimeout=10 file.txt username@server.example.com:/path/
📊
SCP Performance & Security

Optimize performance and enhance security.

Performance and security options

Optimization Tips:

# Use faster cipher
scp -c chacha20-poly1305@openssh.com largefile.iso user@host:/path/

# Enable compression for text files
scp -C documentation.txt user@host:/path/

# Batch mode (no password prompts)
scp -B file.txt user@host:/path/

# Use IPv4 or IPv6 specifically
scp -4 file.txt user@host:/path/  # IPv4 only
scp -6 file.txt user@host:/path/  # IPv6 only

# Specify config file
scp -F ~/.ssh/config file.txt myserver:/path/

# Use jump host
scp -J jumpuser@jumphost file.txt user@targethost:/path/

SFTP - SSH File Transfer Protocol

📂
Interactive SFTP Session

Interactive file transfer and management.

sftp [options] [user@]hostname

Basic SFTP Commands:

  • get file.txt - Download file
  • put file.txt - Upload file
  • ls - List remote files
  • lls - List local files

Examples:

# Start SFTP session
sftp username@server.example.com

# SFTP commands:
ls                    # List remote files
lls                   # List local files
cd /path              # Change remote directory
lcd /local/path       # Change local directory
get file.txt          # Download file
put file.txt          # Upload file
mget *.txt           # Download multiple files
mput *.txt           # Upload multiple files
mkdir newdir          # Create remote directory
rm file.txt           # Remove remote file
rename old new        # Rename remote file
chmod 755 file.txt    # Change permissions
df                    # Show disk usage
exit                  # Exit SFTP

# Batch SFTP with script
echo "put file.txt" | sftp username@server.example.com
🔧
Advanced SFTP Usage

Advanced file operations and scripting.

SFTP advanced features

Advanced Operations:

# SFTP with specific port
sftp -P 2222 username@server.example.com

# SFTP with identity file
sftp -i ~/.ssh/id_rsa username@server.example.com

# Recursive directory transfer
sftp -r username@server.example.com

# Batch file with multiple commands
sftp -b commands.txt username@server.example.com

# Contents of commands.txt:
put file1.txt
put file2.txt
mkdir backup
cd backup
put file3.txt
exit

# Preserve file timestamps
sftp -p username@server.example.com

# Limit bandwidth
sftp -l 1000 username@server.example.com  # 1000 KB/s
SFTP Automation

Automate file transfers with scripts and configurations.

SFTP automation techniques

Automation Examples:

# Simple backup script
#!/bin/bash
sftp -b - username@server.example.com <

File Transfer Methods Comparison

Feature SCP SFTP Rsync over SSH
Speed Fast Medium Very Fast
Resume Support No Yes Yes
Interactive No Yes No
File Management Basic Advanced Basic
Best For Simple transfers Interactive use Large/sync transfers

SSH Server Configuration

🖥️
sshd_config Basics

Essential SSH server configuration for security and functionality.

/etc/ssh/sshd_config

Basic Configuration:

# /etc/ssh/sshd_config
Port 22
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes

# Allow specific users
AllowUsers username admin deploy
AllowGroups ssh-users

# X11 forwarding
X11Forwarding yes
X11DisplayOffset 10

# Security settings
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
MaxSessions 10

# Restart service after changes
sudo systemctl restart sshd
🛡️
SSH Security Hardening

Advanced security configurations to protect SSH servers.

Security-focused sshd_config

Security Hardening:

# /etc/ssh/sshd_config - Security hardened
Port 2222  # Change default port
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no

# Cryptographic settings
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com

# Rate limiting
MaxAuthTries 3
MaxStartups 10:30:100
LoginGraceTime 60

# Restrict access
AllowUsers admin deploy
AllowGroups ssh-users
DenyUsers baduser
DenyGroups badgroup

# Logging
LogLevel VERBOSE
SyslogFacility AUTH
🔧
SSH Server Management

Manage SSH service and troubleshoot issues.

SSH service management commands

Service Management:

# Check SSH service status
sudo systemctl status ssh
sudo systemctl status sshd

# Start/stop/restart SSH service
sudo systemctl start sshd
sudo systemctl stop sshd
sudo systemctl restart sshd
sudo systemctl reload sshd

# Enable SSH at boot
sudo systemctl enable sshd

# Check SSH configuration syntax
sudo sshd -t

# View SSH connections
sudo netstat -tulpn | grep :22
sudo ss -tulpn | grep :22

# View SSH logs
sudo journalctl -u sshd -f
sudo tail -f /var/log/auth.log | grep ssh

Practical Examples & Use Cases

Real-World SSH, SCP, and SFTP Scenarios

# 1. Automated Backup Script
#!/bin/bash
# Backup important files to remote server
BACKUP_FILE="backup-$(date +%Y%m%d).tar.gz"
tar -czf /tmp/$BACKUP_FILE /important/data/
scp /tmp/$BACKUP_FILE user@backup-server:/backups/
ssh user@backup-server "ls -la /backups/$BACKUP_FILE"
rm /tmp/$BACKUP_FILE

# 2. Remote Database Backup
#!/bin/bash
# Dump database and transfer securely
ssh dba@dbserver "pg_dump mydb > /tmp/mydb.sql"
scp dba@dbserver:/tmp/mydb.sql .
ssh dba@dbserver "rm /tmp/mydb.sql"

# 3. Multi-Server Command Execution
#!/bin/bash
# Run command on multiple servers
SERVERS=("web1.example.com" "web2.example.com" "db.example.com")

for server in "${SERVERS[@]}"; do
    echo "=== $server ==="
    ssh admin@$server "uptime; free -h; df -h"
    echo
done

# 4. Secure File Sync
#!/bin/bash
# Sync directory to multiple servers
LOCAL_DIR="/data/"
REMOTE_SERVERS=("server1" "server2" "server3")

for server in "${REMOTE_SERVERS[@]}"; do
    rsync -avz -e ssh $LOCAL_DIR/ admin@$server:/backup/data/
done

# 5. Port Forwarding/Tunneling
# Local port forwarding (access remote service locally)
ssh -L 8080:localhost:80 user@webserver

# Remote port forwarding (expose local service remotely)
ssh -R 9090:localhost:3000 user@remoteserver

# Dynamic SOCKS proxy
ssh -D 1080 user@proxyserver

# 6. Jump Host/Bastion Host Setup
# Direct connection through jump host
ssh -J jumpuser@jumphost user@targetserver

# In ~/.ssh/config for persistent setup
Host targetserver
    HostName target.example.com
    User appuser
    ProxyJump jumpuser@bastion.example.com

# 7. SSH Connection Sharing
# Reuse existing connections (faster subsequent connections)
Host *
    ControlMaster auto
    ControlPath ~/.ssh/control-%r@%h:%p
    ControlPersist 600

# 8. Automated Deployment
#!/bin/bash
# Deploy application to multiple servers
APP_SERVERS=("app1" "app2" "app3")
VERSION="1.2.3"

for server in "${APP_SERVERS[@]}"; do
    echo "Deploying to $server"
    scp app-$VERSION.tar.gz deploy@$server:/tmp/
    ssh deploy@$server "tar -xzf /tmp/app-$VERSION.tar.gz -C /opt/app/ && systemctl restart app"
done

# 9. Monitoring Script
#!/bin/bash
# Check multiple servers' health
SERVERS=("web1" "web2" "db1" "cache1")

for server in "${SERVERS[@]}"; do
    echo "=== Health Check: $server ==="
    ssh monitor@$server "
        echo 'Uptime:'; uptime
        echo 'Memory:'; free -h
        echo 'Disk:'; df -h / 
        echo 'Load:'; cat /proc/loadavg
    " 2>/dev/null || echo "$server: Connection failed"
    echo
done

# 10. SSH Tunnel for Database Access
# Secure database connection through SSH tunnel
ssh -L 5432:localhost:5432 user@dbserver
# Now connect to localhost:5432 to access remote database securely

# 11. File Transfer with Progress
# Use rsync for progress indication
rsync -avz --progress largefile.iso user@server:/backup/

# Or use pv with SSH
tar -czf - /large/directory/ | pv | ssh user@server "tar -xzf - -C /backup/"

# 12. Backup with Rotation
#!/bin/bash
# Backup with file rotation on remote server
BACKUP_NAME="backup-$(date +%Y%m%d-%H%M%S).tar.gz"
tar -czf - /important/data/ | ssh user@backup-server "cat > /backups/$BACKUP_NAME"
ssh user@backup-server "find /backups/ -name 'backup-*.tar.gz' -mtime +7 -delete"

# 13. Secure Copy with Verification
#!/bin/bash
# Copy file and verify checksum
FILE="important.dat"
scp $FILE user@server:/backup/
LOCAL_MD5=$(md5sum $FILE | awk '{print $1}')
REMOTE_MD5=$(ssh user@server "md5sum /backup/$FILE" | awk '{print $1}')

if [ "$LOCAL_MD5" = "$REMOTE_MD5" ]; then
    echo "Transfer verified successfully"
else
    echo "Transfer verification failed"
    exit 1
fi

# 14. Bulk User Creation
#!/bin/bash
# Create users on multiple servers with SSH keys
USERNAME="newuser"
SERVERS=("server1" "server2" "server3")

for server in "${SERVERS[@]}"; do
    ssh admin@$server "
        sudo useradd -m -s /bin/bash $USERNAME
        sudo mkdir -p /home/$USERNAME/.ssh
        echo '$(cat ~/.ssh/id_rsa.pub)' | sudo tee /home/$USERNAME/.ssh/authorized_keys
        sudo chown -R $USERNAME:$USERNAME /home/$USERNAME/.ssh
        sudo chmod 700 /home/$USERNAME/.ssh
        sudo chmod 600 /home/$USERNAME/.ssh/authorized_keys
    "
done

# 15. Emergency Access Script
#!/bin/bash
# Emergency access with multiple fallback methods
PRIMARY_SERVER="server1.example.com"
BACKUP_SERVERS=("server2.example.com" "server3.example.com")

if ssh -o ConnectTimeout=5 admin@$PRIMARY_SERVER "echo 'Primary OK'"; then
    echo "Connected to primary server"
else
    echo "Primary server down, trying backups..."
    for backup in "${BACKUP_SERVERS[@]}"; do
        if ssh -o ConnectTimeout=5 admin@$backup "echo 'Backup OK'"; then
            echo "Connected to backup: $backup"
            break
        fi
    done
fi

Common Use Cases

System Administration

  • Remote Server Management: Command-line administration of multiple servers
  • Automated Backups: Secure transfer of backup files
  • Log Collection: Transfer log files for analysis
  • Configuration Management: Distribute configuration files

Development & Deployment

  • Code Deployment: Transfer application files to servers
  • Database Management: Secure database access and backups
  • File Synchronization: Keep development environments in sync
  • CI/CD Pipelines: Automated deployment scripts

Security & Compliance

  • Secure File Transfer: Encrypted file transfers
  • Audit Trails: Logged access and file transfers
  • Access Control: Key-based authentication
  • Network Security: Tunneling for secure service access

Troubleshooting & Best Practices

🐛

Common SSH Issues

Diagnose and fix common SSH problems.

Troubleshooting commands

Diagnostic Commands:

# Test SSH connection with verbose output
ssh -vvv user@hostname

# Check if port is open
telnet hostname 22
nc -zv hostname 22

# Verify SSH keys
ssh-keygen -l -f ~/.ssh/id_rsa.pub

# Check SSH configuration
ssh -G hostname

# Test specific authentication method
ssh -o PreferredAuthentications=publickey user@hostname
ssh -o PreferredAuthentications=password user@hostname

# Check server configuration
sudo sshd -T
🛡️

Security Best Practices

Enhance SSH security with best practices.

Security recommendations

Security Tips:

# Use ED25519 keys (more secure than RSA)
ssh-keygen -t ed25519 -a 100

# Disable password authentication
# In sshd_config: PasswordAuthentication no

# Use strong ciphers and algorithms
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
KexAlgorithms curve25519-sha256@libssh.org

# Implement two-factor authentication
# Use Google Authenticator or similar

# Regular key rotation
# Generate new keys every 6-12 months

# Monitor SSH access logs
sudo grep sshd /var/log/auth.log

Performance Optimization

Optimize SSH performance for better experience.

Performance tuning

Optimization Tips:

# Enable connection sharing
Host *
    ControlMaster auto
    ControlPath ~/.ssh/control-%r@%h:%p
    ControlPersist 600

# Use compression for slow connections
ssh -C user@hostname

# Optimize for high-latency connections
ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 user@hostname

# Use faster encryption algorithms
ssh -c chacha20-poly1305@openssh.com user@hostname

# Batch mode for scripts
ssh -o BatchMode=yes user@hostname "command"
Important Considerations:
• Always use key-based authentication instead of passwords
• Regularly rotate SSH keys and update authorized_keys files
• Use non-standard ports to reduce automated attacks
• Implement fail2ban or similar to block brute force attempts
• Keep SSH client and server software updated
• Use strong encryption algorithms and disable weak ones
• Monitor SSH logs for suspicious activity
• Have backup access methods in case SSH configuration fails
Pro Tips:
• Use ~/.ssh/config for host-specific settings and aliases
• Enable connection sharing for faster subsequent connections
• Use ssh -v or ssh -vv for debugging connection issues
• Consider using tmux or screen for persistent sessions
• Use rsync over SSH for efficient file synchronization
• Implement SSH jump hosts for accessing internal networks securely
• Use SSH agent forwarding carefully and only when necessary
• Regularly audit and clean up old authorized_keys entries

Key Takeaways

SSH, SCP, and SFTP form the foundation of secure remote access and file transfer in Linux environments. Mastering these tools enables efficient system administration, secure file management, and automated workflows. Remember that security should always be a priority - use key-based authentication, keep software updated, and follow security best practices. Whether you're managing a single server or an entire infrastructure, these skills are essential for modern system administration and DevOps practices.

Next Step: Explore advanced SSH topics like SSH certificates, multi-factor authentication, SSH bastion hosts, and automated SSH key management with tools like HashiCorp Vault.