Using SSH keys is a secure way to authenticate with remote servers and services (like GitHub, remote servers via SSH, etc.) without needing to type your password each time. Here's a complete guide on how to generate, configure, and use SSH keys across typical use cases.
SSH keys are a pair of cryptographic keys used for secure authentication:
~/.ssh/id_rsa
): Kept secret on your machine.~/.ssh/id_rsa.pub
): Shared with the remote server or service.ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-t rsa
: Type of key (RSA)-b 4096
: Key length (bits)-C
: A comment, usually your emailYouβll see:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/youruser/.ssh/id_rsa):
Press Enter to accept the default path.
Enter passphrase (empty for no passphrase):
You can optionally set a passphrase (adds extra security). Your keys are now saved in ~/.ssh/id_rsa
and ~/.ssh/id_rsa.pub
.
ssh-copy-id
(easiest)ssh-copy-id user@remote_host
This appends your public key to ~/.ssh/authorized_keys
on the server.
cat ~/.ssh/id_rsa.pub
Copy the output, then on the remote server:
mkdir -p ~/.ssh
echo "your_copied_public_key" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh
ssh user@remote_host
If everything's set up, it will log you in without a password.
cat ~/.ssh/id_rsa.pub
ssh -T git@github.com
You should see:
Hi username! You've successfully authenticated.
ssh -i ~/.ssh/your_custom_key user@remote_host
~/.ssh/config
:Host myserver
HostName 192.168.0.10
User myuser
IdentityFile ~/.ssh/my_custom_key
Then just run:
ssh myserver
ssh -A user@jump_host
This allows your SSH agent and keys to be used on the remote host, useful for SSHing from a remote server into another server (hop).
To avoid entering your passphrase repeatedly:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
You can also automate this on login (e.g., via .bashrc
, .zshrc
, or macOS Keychain).
cat ~/.ssh/authorized_keys
You should see your public key listed there. If login fails, check:
~/.ssh
should be 700
authorized_keys
should be 600
sshd
on the server allows key-based authAction | Command/Path |
---|---|
Generate Key | ssh-keygen -t rsa -b 4096 -C "email" |
View Public Key | cat ~/.ssh/id_rsa.pub |
Copy to Remote | ssh-copy-id user@host |
Connect via SSH | ssh user@host |
GitHub Key Test | ssh -T git@github.com |
Use Specific Key | ssh -i path/to/key user@host |
SSH Config File | ~/.ssh/config |
Add Key to Agent | ssh-add ~/.ssh/id_rsa |
If you want a quick script or config tailored to your use case (e.g., auto-loading keys, working with multiple remotes, or integrating with Git), let me know!