Skip to content
ssh Command in Linux — Secure Shell with Practical Examples

ssh Command in Linux — Secure Shell with Practical Examples

DodaTech Updated Jun 20, 2026 7 min read

SSH (Secure Shell) is the standard protocol for securely connecting to remote Linux servers. It encrypts all traffic — including passwords, commands, and data — making it the foundation of remote server administration.

What You’ll Learn

By the end of this tutorial, you’ll know how to connect to remote servers, set up key-based authentication, configure ~/.ssh/config for convenience, forward ports locally and remotely, use SCP and SFTP for file transfer, use jump hosts, enable multiplexing, configure keep-alive, and debug connection issues.

Why SSH Matters

Every Linux server you manage — from a single VPS to a fleet of cloud instances — is accessed via SSH. DodaZIP uses SSH for server provisioning and deployment, and Durga Antivirus Pro uses SSH tunnels for secure database connections across data centers.

SSH Learning Path

    flowchart LR
  A[rsync Command] --> B[SSH Command<br/>You are here]
  B --> C[Server Setup]
  C --> D[Security Hardening]
  D --> E[System Administration]
  style B fill:#f90,color:#fff
  
Prerequisites: A remote Linux server to connect to. Basic knowledge of Linux fundamentals and essential commands.

Syntax Overview

ssh [options] user@host [command]
OptionDescription
-p PORTSpecify port (default: 22)
-i keyfileUse specific identity file
-L port:host:hostportLocal port forwarding
-R port:host:hostportRemote port forwarding
-J user@jump-hostConnect via jump host
-v, -vv, -vvvVerbose (debug) mode
-NDon’t execute remote command (port forwarding only)
-fBackground SSH
-o Option=ValueSet SSH option

10 Practical Examples

1. Basic SSH Connection

Connect to a remote server:

ssh alice@192.168.1.100
The authenticity of host '192.168.1.100 (192.168.1.100)' can't be established.
ED25519 key fingerprint is SHA256:abc123...
Are you sure you want to continue connecting? yes
alice@192.168.1.100's password:

On first connection, you see the host key fingerprint. After verifying and accepting, you’re prompted for the password. Subsequent connections skip the fingerprint prompt.

2. Key-Based Authentication

Generate an SSH key pair:

ssh-keygen -t ed25519 -C "alice@workstation"
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/alice/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/alice/.ssh/id_ed25519
Your public key has been saved in /home/alice/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:xyz789 alice@workstation

Copy the public key to the server:

ssh-copy-id alice@192.168.1.100
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/alice/.ssh/id_ed25519.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s)
alice@192.168.1.100's password:

Number of key(s) added: 1

Now connect without a password:

ssh alice@192.168.1.100

3. SSH Config File

Create ~/.ssh/config for convenient connection shortcuts:

Host webserver
    HostName 192.168.1.100
    User alice
    Port 22
    IdentityFile ~/.ssh/id_ed25519

Host database
    HostName db.internal.company.com
    User dbadmin
    Port 2222
    IdentityFile ~/.ssh/db_key
    LocalForward 3306 localhost:3306

Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3

Now connect with a simple name:

ssh webserver
Welcome to Ubuntu 24.04 LTS (GNU/Linux 6.8.0-35-generic x86_64)

4. Port Forwarding (Local)

Forward local port 8080 to a remote service on port 80:

ssh -L 8080:localhost:80 alice@webserver

Now open http://localhost:8080 in your browser — it forwards to http://webserver:80 through the SSH tunnel.

Forward to a third machine:

ssh -L 9090:internal-db:5432 alice@bastion-host

Access the remote PostgreSQL database at localhost:9090.

5. Remote Port Forwarding

Expose a local service on a remote server:

# Local machine runs a web app on port 3000
ssh -R 8080:localhost:3000 alice@webserver

Now anyone who connects to webserver:8080 is tunneled to your local port 3000.

6. File Transfer with SCP

Copy a file to a remote server:

scp report.pdf alice@192.168.1.100:/home/alice/
report.pdf                       100% 234KB 1.2MB/s   00:00

Copy a file from a remote server:

scp alice@192.168.1.100:/var/log/syslog ./remote-syslog.log

Copy an entire directory:

scp -r /home/projects/ alice@192.168.1.100:/backup/projects/

7. SFTP — Interactive File Transfer

Start an SFTP session:

sftp alice@192.168.1.100
Connected to 192.168.1.100.
sftp>

Useful SFTP commands:

sftp> ls -la                          # List remote files
sftp> cd /var/www                     # Change remote directory
sftp> get index.html                  # Download file
sftp> put local-file.txt              # Upload file
sftp> get -r logs/                    # Download directory recursively
sftp> put -r build/                   # Upload directory recursively
sftp> bye                             # Exit

8. Jump Hosts

Connect to a server that’s only reachable through a bastion:

ssh -J alice@bastion.example.com alice@internal-server.local

With SSH config:

Host internal
    HostName internal-server.local
    User alice
    ProxyJump alice@bastion.example.com

Then simply:

ssh internal

9. Multiplexing (Connection Sharing)

Reuse an existing SSH connection to avoid re-authentication:

Host *
    ControlMaster auto
    ControlPath ~/.ssh/controlmasters/%r@%h:%p
    ControlPersist 10m
mkdir -p ~/.ssh/controlmasters

Now the first SSH connection authenticates; subsequent connections to the same host reuse the established connection.

10. Keep-Alive and Debug Mode

Prevent SSH from disconnecting due to inactivity:

ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 alice@server

Debug a connection issue:

ssh -vvv alice@192.168.1.100
OpenSSH_9.6p1, OpenSSL 3.0.13
debug1: Connecting to 192.168.1.100 [192.168.1.100] port 22.
debug1: Connection established.
debug1: Local version string SSH-2.0-OpenSSH_9.6
debug1: Remote protocol version 2.0, remote software version OpenSSH_8.9
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred publickey,keyboard-interactive,password
debug1: Offering public key: /home/alice/.ssh/id_ed25519 ED25519 SHA256:xyz789
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.

Common Use Cases

Run a Single Command Remotely

ssh alice@server "uptime && df -h /"

Tunneling a Database Connection

ssh -L 3306:localhost:3306 -N -f alice@db-server
# Now connect to localhost:3306 as if it's the remote database

Copy SSH Key to Multiple Servers

for host in server1 server2 server3; do
    ssh-copy-id alice@$host
done

Agent Forwarding

ssh -A alice@bastion
# From bastion, you can now SSH to other servers using your local keys

Common Mistakes

1. Using Password Authentication in Production

Password-based SSH is vulnerable to brute-force attacks. Always use key-based authentication and disable password auth in /etc/ssh/sshd_config on production servers.

2. Leaving Keys Without Passphrases

An unprotected private key is a security risk. Always add a passphrase, and use ssh-agent to cache it.

3. Incorrect Permissions on ~/.ssh

SSH refuses to use keys if permissions are too open:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
chmod 600 ~/.ssh/config

4. Confusing -L and -R

-L (local) forwards a local port to a remote destination. -R (remote) forwards a remote port to a local destination.

5. Forgetting to Add Key to ssh-agent

Without ssh-add, you’ll type your passphrase every time. Add once: ssh-add ~/.ssh/id_ed25519.

Practice Questions

1. How do you generate an Ed25519 SSH key pair?

ssh-keygen -t ed25519 -C "your@email.com"

2. What does ssh -L 8080:localhost:80 user@host do?

It forwards connections on your local port 8080 to port 80 on the remote host through the SSH tunnel.

3. How do you copy a file from a remote server to your local machine with SCP?

scp user@host:/remote/path/file.txt ./local-dir/

4. What’s the purpose of the SSH config file?

It stores per-host settings (hostname, user, port, key file, port forwards) so you can connect with simple aliases like ssh webserver.

5. Challenge: Write an SSH command that connects to a remote server using a non-standard port (2222), with a specific identity file, setting a keep-alive of 30 seconds.

ssh -p 2222 -i ~/.ssh/mykey -o ServerAliveInterval=30 alice@192.168.1.100

Mini Project: SSH Connection Manager

#!/bin/bash
# ssh_manager.sh — Simple SSH connection manager
# Usage: ./ssh_manager.sh [list|connect|add]

CONFIG_FILE="$HOME/.ssh/config"

list_hosts() {
    echo "=== Configured Hosts ==="
    grep "^Host " "$CONFIG_FILE" | awk '{print $2}' | grep -v '\*'
}

case "${1:-list}" in
    list)
        list_hosts
        ;;
    connect)
        HOST="$2"
        if grep -q "^Host $HOST$" "$CONFIG_FILE" 2>/dev/null; then
            echo "Connecting to $HOST..."
            ssh "$HOST"
        else
            echo "Error: Host '$HOST' not found in config."
            echo "Available hosts:"
            list_hosts
            exit 1
        fi
        ;;
    add)
        echo "Adding new host to $CONFIG_FILE"
        read -p "Host alias: " alias
        read -p "Hostname (IP or domain): " hostname
        read -p "User: " user
        read -p "Port [22]: " port
        port=${port:-22}
        
        cat >> "$CONFIG_FILE" << EOF

Host $alias
    HostName $hostname
    User $user
    Port $port
EOF
        echo "Host '$alias' added successfully."
        ;;
    *)
        echo "Usage: $0 [list|connect|add]"
        exit 1
        ;;
esac

Expected output (list):

=== Configured Hosts ===
webserver
database
internal

FAQ

What’s the difference between SSH and SSL/TLS?
SSH is primarily for secure remote shell access and command execution. SSL/TLS secures HTTP (HTTPS) and other application protocols. They use different protocols and ports (SSH: 22, HTTPS: 443).
How do I disable password authentication in SSH?
Edit /etc/ssh/sshd_config, set PasswordAuthentication no, then restart: sudo systemctl restart sshd. Always ensure key-based auth works before disabling passwords.
What is SSH agent forwarding?
ssh -A forwards your local SSH agent to the remote server, allowing you to authenticate from the remote server to other servers using your local keys. Use with caution in untrusted environments.
How do I fix “WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED”?
This means the remote server’s host key changed (possible MITM attack or server reinstall). Verify the change with the admin, then remove the old key: ssh-keygen -R hostname.

What’s Next

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro