🔑
SSH cheat sheet
SSH commands for connecting, key management, file copying and port forwarding. Put frequently used options in ~/.ssh/config so you can type just ssh myserver.
Click any command to copy it.
Connect
| Command | What it does |
|---|---|
ssh user@host | Connect to a server. |
ssh -p 2222 user@host | Use a non-default port. |
ssh -i ~/.ssh/key user@host | Use a specific private key. |
ssh user@host 'command' | Run one command remotely and exit. |
ssh -J bastion user@target | Connect through a jump host. |
ssh -v user@host | Verbose output for debugging connection problems. |
ssh -o ServerAliveInterval=60 user@host | Send keep-alives so idle sessions are not dropped. |
Keys
| Command | What it does |
|---|---|
ssh-keygen -t ed25519 -C "comment" | Generate a modern key pair. |
ssh-copy-id user@host | Install your public key on a server. |
ssh-keygen -lf ~/.ssh/id_ed25519.pub | Show a key's fingerprint. |
eval "$(ssh-agent -s)" | Start an SSH agent in this shell. |
ssh-add ~/.ssh/id_ed25519 | Add a key to the agent. |
ssh-keygen -R host | Remove a host from known_hosts (after a legitimate server rebuild). |
Copy files
| Command | What it does |
|---|---|
scp file.txt user@host:/path/ | Copy a file to a server. |
scp user@host:/path/file.txt . | Copy a file from a server. |
scp -r dir/ user@host:/path/ | Copy a directory recursively. |
sftp user@host | Open an interactive file-transfer session. |
rsync -avzP -e ssh src/ user@host:/path/ | Efficient, resumable copy (see the rsync cheat sheet). |
Tunnels
| Command | What it does |
|---|---|
ssh -L 8080:localhost:80 user@host | Local forward: open localhost:8080 to reach port 80 on the server side. |
ssh -R 9000:localhost:3000 user@host | Remote forward: expose your local port 3000 as port 9000 on the server. |
ssh -D 1080 user@host | Start a SOCKS proxy on local port 1080. |
ssh -N -f -L 5432:db.internal:5432 user@bastion | Background tunnel to an internal database through a bastion. |
Config and permissions
| Command | What it does |
|---|---|
chmod 700 ~/.ssh | The .ssh directory must be private. |
chmod 600 ~/.ssh/id_ed25519 ~/.ssh/authorized_keys | Private keys and authorized_keys must not be readable by others. |
Host myserver
HostName 203.0.113.10
User deploy
Port 2222
IdentityFile ~/.ssh/key | Example ~/.ssh/config entry; then use: ssh myserver. |
sshd -t | Test the server configuration for syntax errors before restarting sshd. |
Frequently asked questions
Why does SSH say my key permissions are too open?
SSH refuses private keys readable by others. Run chmod 600 on the key and chmod 700 on ~/.ssh.
How do I stop typing the long command every time?
Add a Host block to ~/.ssh/config with HostName, User, Port and IdentityFile, then connect with ssh followed by the host alias.