Skip to main content

62 entries · 7 sections

SSH Cheat Sheet

SSH from first connection to port forwarding: generating and managing keys, the config file that removes most of the typing, copying files, tunnels, agent forwarding, and how to read the two error messages everybody eventually hits.

Connecting

SyntaxWhat it does
ssh user@hostConnect to a host as a given user.
ssh -p 2222 user@hostUse a non-default port. Note the lower-case p — scp uses a capital one.
ssh -i ~/.ssh/id_ed25519 user@hostUse a specific private key.
ssh user@host "uptime"Run one command and exit, without an interactive shell.
ssh -t user@host "sudo -i"Force a pseudo-terminal, which interactive remote commands need.
ssh -v user@hostVerbose output; -vvv for the full handshake. The first step of every SSH debug.
ssh -J jump@bastion user@internalHop through a bastion host in a single command.
ssh -o StrictHostKeyChecking=accept-new user@hostTrust a new host key on first sight, but still refuse a changed one.
ssh -N -f user@hostRun no command and go to the background. Used for tunnels.
exit or Ctrl-DClose the session.

Keys

SyntaxWhat it does
ssh-keygen -t ed25519 -C "you@example.com"Generate a modern key pair. Ed25519 is the current default choice.
ssh-keygen -t rsa -b 4096Generate an RSA key, for the occasional system that will not accept Ed25519.
ssh-keygen -l -f ~/.ssh/id_ed25519.pubPrint a key's fingerprint, to compare against what a service shows you.
ssh-keygen -p -f ~/.ssh/id_ed25519Change or add a passphrase on an existing key.
ssh-keygen -y -f ~/.ssh/id_ed25519Regenerate the public key from the private one.
ssh-copy-id user@hostAppend your public key to the server's authorized_keys with the right permissions.
ssh-keyscan host >> ~/.ssh/known_hostsRecord a host key non-interactively, for scripts and CI.
ssh-keygen -R hostRemove a stale host key after a server has been rebuilt.
chmod 600 ~/.ssh/id_ed25519Private keys must not be group- or world-readable or SSH refuses to use them.
chmod 700 ~/.sshThe directory itself has to be private too.

The agent

SyntaxWhat it does
eval "$(ssh-agent -s)"Start an agent in the current shell.
ssh-add ~/.ssh/id_ed25519Load a key into the agent so you type the passphrase once per session.
ssh-add -lList the keys the agent is currently holding.
ssh-add -DMake the agent forget every key.
ssh-add --apple-use-keychain keyStore the passphrase in the macOS keychain so it survives a reboot.
ssh -A user@hostForward your agent to the remote host. Convenient, and a genuine trust decision — root there can use your keys.
AddKeysToAgent yesA config option that adds a key to the agent the first time you use it.

~/.ssh/config

SyntaxWhat it does
Host prodStart a block. After it, ssh prod applies everything indented below.
HostName 203.0.113.10The real address the alias points at.
User deployThe default username for this host.
Port 2222The default port for this host.
IdentityFile ~/.ssh/prod_ed25519Which key to offer.
IdentitiesOnly yesOffer only that key rather than every key the agent holds — the fix for "too many authentication failures".
ProxyJump bastionAlways route through a jump host, without typing -J.
ServerAliveInterval 60Send a keepalive every minute so idle sessions survive NAT and firewall timeouts.
ForwardAgent yesForward the agent for this host only, rather than globally.
Host *A block of defaults for every host. Put it last: for each option, the first match in the file wins.

Copying files

SyntaxWhat it does
scp file user@host:/path/Copy a file up to a server.
scp user@host:/path/file .Copy a file back down.
scp -r dir/ user@host:/path/Copy a directory recursively.
scp -P 2222 file user@host:The port flag is capital P for scp and lower-case p for ssh.
rsync -avz src/ user@host:/dest/Sync over SSH, transferring only what changed. Note the trailing slash on src.
rsync -avz --progress --partial ...Show progress and allow an interrupted transfer to resume.
sftp user@hostAn interactive transfer session with put, get, ls and cd.
tar czf - dir | ssh user@host "tar xzf - -C /dest"Stream a directory across in one pipe, without a temporary archive.

Tunnels and forwarding

SyntaxWhat it does
ssh -L 8080:localhost:80 user@hostLocal forward: your port 8080 reaches port 80 as seen from the remote host.
ssh -L 5432:db.internal:5432 user@bastionReach a database that only the bastion can see.
ssh -R 9000:localhost:3000 user@hostRemote forward: expose your local port 3000 as port 9000 on the server.
ssh -D 1080 user@hostRun a SOCKS5 proxy through the server, for a browser to use.
ssh -N -L 8080:localhost:80 user@hostA tunnel with no shell attached.
GatewayPorts yesThe server setting a remote forward needs before it will accept outside connections.
AllowTcpForwarding noThe server setting that disables tunnelling entirely.

Server side and troubleshooting

SyntaxWhat it does
~/.ssh/authorized_keysThe list of public keys allowed to log in as that user.
/etc/ssh/sshd_configThe SSH server's configuration file.
PasswordAuthentication noTurn off password logins once keys work. The single biggest hardening win.
PermitRootLogin noStop direct root logins; use a normal account and sudo.
sudo sshd -tCheck the config for syntax errors before you restart and lock yourself out.
sudo systemctl restart sshApply configuration changes. The unit is ssh on Debian and Ubuntu, sshd on RHEL family.
Permission denied (publickey)No key was accepted: wrong key, wrong username, key not in authorized_keys, or bad file permissions.
Host key verification failedThe server's key changed. Find out why, then clear it with ssh-keygen -R host.
sudo journalctl -u ssh -fWatch authentication attempts live while you debug.
ssh -vvv user@hostShows exactly which keys were offered and why each one was refused.

Worth knowing

  • Keep an existing SSH session open whenever you edit sshd_config. Run sudo sshd -t to check the syntax, restart the service, then prove you can open a second session before closing the first. That habit is the difference between a typo and a trip to the console.
  • ~/.ssh/config removes most of the typing and most of the mistakes. A four-line Host block gives you ssh prod instead of ssh -i ~/.ssh/prod_ed25519 -p 2222 deploy@203.0.113.10, and scp, rsync, git and anything else that shells out to ssh all read the same file.
  • "Too many authentication failures" means the agent offered several keys and the server cut the connection before reaching the right one. Add IdentitiesOnly yes together with an explicit IdentityFile in your config for that host, and only the correct key is offered.

Try a snippet instead of reading about it

Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.

Open the editor

SSH — common questions

How do I generate an SSH key?
Run ssh-keygen -t ed25519 -C "you@example.com", accept the default path, and set a passphrase. That creates ~/.ssh/id_ed25519 (keep it secret) and ~/.ssh/id_ed25519.pub (the one you upload). Use ssh-copy-id user@host to install it on a server, or paste the .pub contents into GitHub, GitLab or your cloud console.
What is the difference between Ed25519 and RSA keys?
Ed25519 keys are much shorter, faster to verify, and are considered at least as strong as a 4096-bit RSA key. They are supported by every current OpenSSH, GitHub, GitLab and major cloud provider. Generate RSA at 4096 bits only when you hit an old system or appliance that has not caught up.
Why do I keep getting Permission denied (publickey)?
In order of likelihood: the public key is not in the server's ~/.ssh/authorized_keys for that user, you are connecting as the wrong username, the permissions are too open (the key needs 600, ~/.ssh needs 700 and the home directory must not be group-writable), or the agent offered a different key. Run ssh -vvv user@host — it prints every key it tried and how the server responded.
How does SSH port forwarding work?
ssh -L 8080:target:80 user@host opens port 8080 on your machine and tunnels anything sent there through the SSH connection, out to target:80 as resolved from the remote host — which is how you reach an internal database through a bastion. ssh -R does the reverse, opening a port on the server that reaches back into your machine, and ssh -D turns the connection into a SOCKS proxy.