Computing

SSH: connecting to a server securely


What is SSH?

SSH (Secure Shell) is a protocol that lets you access a remote machine over an encrypted channel. It’s used to administer servers, transfer files and create network tunnels.

Connecting

ssh [email protected]
ssh -p 2222 [email protected]   # custom port

On the first connection, SSH asks you to confirm the server’s fingerprint. It is then saved in ~/.ssh/known_hosts, which lets you detect a suspicious change.

Key-based authentication

A key pair is safer than a password. The private key stays on your machine, the public key is placed on the server.

# Generate a key (Ed25519 recommended)
ssh-keygen -t ed25519 -C "mon-commentaire"

# Copy the public key to the server
ssh-copy-id [email protected]

Protect your private key with a passphrase, and never share it.

The ~/.ssh/config file

Avoid retyping the options every time:

Host mon-serveur
    HostName serveur.exemple.com
    User utilisateur
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

You can then simply connect with ssh mon-serveur.

Transferring files

scp fichier.txt mon-serveur:/chemin/destination/
rsync -avz dossier/ mon-serveur:/chemin/destination/

SSH tunnel

To access a remote service through a local port:

ssh -L 8080:localhost:80 mon-serveur

The service is then available at http://localhost:8080.

Best practices

  • Use keys rather than passwords.
  • Disable password login and root login in /etc/ssh/sshd_config (PasswordAuthentication no, PermitRootLogin no).
  • Keep OpenSSH up to date.
  • Use ssh-agent to enter your passphrase only once per session.
  • Restrict access with a firewall or a tool like fail2ban.

Key takeaways

SSH is a basic tool for any administrator or developer. With good key management and a clean config file, it becomes fast and safe to use.