Accessing Servers with SSH Keys
SSH keys are the first thing I set up on any new server. Compared to passwords they're both more secure (nothing to brute-force) and more convenient (no prompt on every login). This is the full setup, from generating a key pair to logging in with it.
π What SSH keys are
An SSH key pair has two halves:
- Private key β stays on your machine and never leaves it.
- Public key β copied to every server you want to access.
The server uses the public key to issue a challenge that only the holder of the private key can answer, so nothing secret ever travels over the wire.
π οΈ Step 1: Generate a key pair (if you don't have one)
BASHssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-t rsaβ use the RSA algorithm.-b 4096β 4096-bit key size for strong security.-C "..."β a label so you can tell your keys apart later.
Press Enter to accept the default location (~/.ssh/id_rsa), then set a passphrase when prompted. The passphrase is optional, but it means a stolen private key file is still useless on its own β worth the small friction.
π Step 2: If you already have a key pair
Check ~/.ssh/ before generating anything β a second key pair when one already exists just creates confusion:
BASHls ~/.ssh
If you see id_rsa (private key) and id_rsa.pub (public key), skip generation and go straight to installing the public key.
π€ Step 3: Add the public key to the server
-
Print your public key and copy the output:
BASHcat ~/.ssh/id_rsa.pub -
Log in to the server with whatever method you currently have (usually a password).
-
Append the key to
authorized_keys:BASHecho "your_public_key_contents" >> ~/.ssh/authorized_keysNote the
>>β a single>would overwrite the file and lock out every key already installed.
π Step 4: Fix the permissions
SSH is strict about this: if these files are too open, it silently ignores them and falls back to password authentication.
BASHchmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys chmod 600 ~/.ssh/id_rsa
π Step 5: Connect
BASHssh -i ~/.ssh/id_rsa username@server_ip
-i ~/.ssh/id_rsaβ which private key to use.username/server_ipβ the account and address of the server.
If the key is in the default location, you can drop the -i flag entirely β ssh looks there on its own. Adjust the command if your server uses a non-default port.
π Troubleshooting
- Connection refused β make sure the SSH service is running on the server.
- Timeout β check that the firewall allows the SSH port (22 by default).
- Still asked for a password β nine times out of ten it's the file permissions from Step 4.
π Conclusion
Once key-based login works, the natural next step is disabling password authentication entirely in sshd_config β at that point, brute-force attempts against your server become pointless.
Happy coding π