SSH Tutorial: From Basics to Advanced Techniques
In this article
- What Is SSH and Why It Matters
- How SSH Works: Keys, Encryption, and Authentication
- Getting Started: Basic SSH Commands
- Key-Based Authentication: Setup and Best Practices
- Advanced Techniques: Tunneling, Agent Forwarding, and Jump Hosts
- Common Problems and Troubleshooting
- SSH Alternatives and When to Use Them
- Security Hardening: Protect Your SSH Server
- Frequently Asked Questions
This comprehensive guide explains SSH (Secure Shell) from the ground up, covering how it works, how to use it for daily tasks, and how to apply advanced techniques for automation, tunneling, and security. You'll learn the exact commands and concepts needed to move from a beginner to a confident SSH user.
What Is SSH and Why It Matters
SSH, or Secure Shell, is a cryptographic network protocol that lets you securely connect to and manage remote computers over an unsecured network like the internet. It was created in 1995 by Tatu Ylönen as a replacement for insecure protocols like Telnet, FTP, and rlogin, which transmitted data, including passwords, in plain text. SSH encrypts all traffic between your local machine and the remote server, protecting against eavesdropping, connection hijacking, and other attacks.
Today, SSH is the backbone of remote server administration, cloud computing, and DevOps. Every time a developer pushes code to GitHub, deploys an application to a cloud server, or manages a Raspberry Pi, SSH is likely involved. It also powers secure file transfers (SFTP), port forwarding, and even encrypted network tunnels for accessing private services.
How SSH Works: Keys, Encryption, and Authentication
SSH uses a client-server model. The SSH server runs on the remote machine and listens on port 22 by default. The SSH client, typically the ssh command on Linux, macOS, or Windows (via PowerShell or Windows Terminal), initiates a connection to the server.
The protocol establishes a secure channel using a combination of asymmetric and symmetric encryption:
- Key exchange: The client and server agree on a session key using a key exchange algorithm like Diffie-Hellman or ECDH. This key is only used for that session.
- Host verification: The server presents its host key (a public key). The client checks if it matches a known host key (stored in
~/.ssh/known_hosts). If not, the client prompts you to verify the fingerprint. - User authentication: You authenticate using either a password (encrypted) or, more securely, a public/private key pair. With key-based authentication, your private key (kept secret on your local machine) signs a challenge from the server, and the server verifies it against your public key (stored in
~/.ssh/authorized_keyson the server).
Once authenticated, all subsequent data is encrypted with the session key using symmetric encryption (e.g., AES). This provides confidentiality and integrity.
Getting Started: Basic SSH Commands
To connect to a remote server, open a terminal and type:
ssh username@hostname
For example, ssh alice@192.168.1.100 or ssh root@example.com. If the server runs on a non-default port, use -p:
ssh -p 2222 alice@hostname
After connecting, you'll get a remote shell where you can run commands. To exit, type exit or press Ctrl+D.
Other essential commands:
scp file.txt user@host:/path/– securely copy a file to the remote server.sftp user@host– start an interactive secure file transfer session.ssh-keygen– generate a new SSH key pair (we'll cover this next).ssh-copy-id user@host– copy your public key to the server's authorized_keys file (Linux/macOS).
Key-Based Authentication: Setup and Best Practices
Password authentication is vulnerable to brute-force attacks. Key-based authentication is more secure and more convenient. Here's how to set it up:
- Generate a key pair on your local machine:
ssh-keygen -t ed25519 -C "your_email@example.com". Ed25519 is a modern, fast, and secure algorithm; RSA (e.g.,-t rsa -b 4096) is also acceptable but slower. - Copy the public key to the server:
ssh-copy-id user@host(or manually append the contents of~/.ssh/id_ed25519.pubto~/.ssh/authorized_keyson the server). - Test the login:
ssh user@host. It should now connect without asking for a password.
Best practices:
- Protect your private key with a strong passphrase. Use
ssh-agentto load the key once and avoid typing the passphrase repeatedly. - Never share your private key.
- Disable password authentication on the server (in
/etc/ssh/sshd_configsetPasswordAuthentication no) after you've set up keys. - Use a different key pair for different servers or services to limit damage if one key is compromised.
Advanced Techniques: Tunneling, Agent Forwarding, and Jump Hosts
Once comfortable with basic SSH, you can unlock powerful features:
Port Forwarding (Tunneling)
SSH can forward ports to securely access services on remote networks. For example, to securely access a web server running on a remote machine's port 80, you can create a local tunnel:
ssh -L 8080:localhost:80 user@remote
Now, browsing to http://localhost:8080 on your local machine will securely reach the remote web server. Reverse tunneling (-R) exposes a local service to the remote side, useful for sharing a local development server with a colleague.
Agent Forwarding
If you need to SSH from one server to another (e.g., to pull a Git repository), you can forward your SSH agent with ssh -A user@server. This allows the remote server to use your local private key without copying it there. Be cautious: agent forwarding should only be used with trusted servers, as a compromised server could use your agent to authenticate to other hosts.
Jump Hosts (Bastion)
In a typical corporate network, you may need to go through a jump host to reach internal servers. You can do this directly:
ssh -J user@bastion user@internal-server
This chains connections, so you only need to authenticate once (if you use agent forwarding).
Common Problems and Troubleshooting
Even experienced users hit issues. Here are common ones and how to fix them:
- Connection refused: The SSH server isn't running, or the port is blocked by a firewall. Check the server status (
systemctl status sshdon systemd systems) and that port 22 is open. - Permission denied (publickey): The server doesn't accept your key. Verify the public key is correctly in
~/.ssh/authorized_keyson the server, and that file permissions are correct (chmod 600 for the file, 700 for the .ssh directory). - Host key verification failed: This happens when the server's host key has changed (e.g., after reinstalling the OS). To fix, remove the old entry from
~/.ssh/known_hostsusingssh-keygen -R hostname. - Connection timed out: Network issue or firewall dropping packets. Use
pingandtelnet host 22to test connectivity. - Too many authentication failures: The client is presenting too many keys. Use
ssh -o IdentitiesOnly=yes -i /path/to/key user@hostto specify the exact key.
SSH Alternatives and When to Use Them
While SSH is the de facto standard for secure remote access, there are alternatives for specific use cases:
- Telnet: Unencrypted, obsolete, never use for sensitive data.
- RDP (Remote Desktop Protocol): For graphical desktop access to Windows machines, not a replacement for SSH.
- VPN: Creates a secure network tunnel, but doesn't provide a shell; you still need SSH to log into servers.
- Mosh (Mobile Shell): A remote shell that roams across network changes and is more responsive on high-latency links. It uses SSH for authentication.
- Web-based terminals: Some cloud providers offer SSH access via a browser, which is convenient but less flexible.
For most administrative tasks, SSH remains the best choice due to its security, flexibility, and ubiquity.
Security Hardening: Protect Your SSH Server
If you run an SSH server, you should secure it against automated attacks. Here are essential steps:
- Use key-based authentication only: Disable password authentication.
- Disable root login: Set
PermitRootLogin noinsshd_configand use a regular user withsudo. - Change the default port: While not a real security measure (security through obscurity), it reduces automated bot scans. Use a high port like 2222.
- Use fail2ban: This tool bans IPs after repeated failed login attempts, mitigating brute-force attacks.
- Keep SSH updated: Always install the latest security patches for OpenSSH.
- Limit users: Use
AllowUsersinsshd_configto restrict who can log in.
Frequently Asked Questions
What is the difference between SSH and SSL/TLS?
SSH is designed for secure remote access and command execution, while SSL/TLS is used to encrypt web traffic (HTTPS), email, and other application protocols. They use different handshake mechanisms and serve different purposes, though both rely on public-key cryptography.
Can I use SSH on Windows?
Yes. Windows 10 and 11 include an OpenSSH client in PowerShell and Windows Terminal. You can also use third-party tools like PuTTY, but the built-in client is now the recommended option.
How do I copy files from a remote server to my local machine?
Use scp user@host:/path/to/remote/file /local/destination/. For directories, add -r. Alternatively, use sftp for an interactive session.
What is SSH agent forwarding and is it safe?
Agent forwarding lets a remote server use your local SSH agent to authenticate to other servers. It's safe only if you trust the remote server completely, because a compromised server could use your agent to access other hosts. Use -A only when necessary.
How do I change my SSH passphrase?
Run ssh-keygen -p -f ~/.ssh/id_ed25519. You'll be prompted for your current passphrase and then the new one.
What is the difference between ~/.ssh/id_rsa and ~/.ssh/id_ed25519?
These are private key files for RSA and Ed25519 algorithms, respectively. Ed25519 is newer, faster, and considered more secure for the same key size. RSA is more widely compatible with older systems. You can have multiple keys in your ~/.ssh directory.