SSH Commands Master Cheat Sheet

Learn Bash scripting from scratch by building 10 practical scripts for backups, file organizing, monitoring, and automation, with clear explanations.

8 min read
AI-assisted

Author's AI disclosure

The author reports using AI to help with this article.

The author confirms reviewing this article.

SSH Commands Master Cheat Sheet

A practical, copy-paste-ready reference for keys, config files, tunnels, file transfers, and fixing the errors everyone hits sooner or later.

Why You Need an SSH Cheat Sheet

SSH (Secure Shell) is how developers and sysadmins log in to servers, push code to Git hosts, copy files, and reach private networks. You use it constantly, yet the flags are easy to forget, and the error messages are famously unhelpful.

This guide covers the commands you will actually use, with short examples you can paste straight into your terminal. It also includes the parts most cheat sheets skip: a config file that removes most of the typing, port forwarding explained in plain language, and a troubleshooting section organized by error message.

Golden rule: when a connection fails, add -v before you guess.

ssh -v user@host        # verbose: shows exactly where it fails
ssh -vvv user@host      # even more detail
man ssh                 # the full manual

The Mental Model in 30 Seconds

Your machine (client)                         Remote machine (server)
---------------------                         ------------------------
~/.ssh/id_ed25519        (private key)        ~/.ssh/authorized_keys   (public keys allowed in)
~/.ssh/id_ed25519.pub    (public key)  ---->  sshd (the SSH daemon, port 22)
~/.ssh/known_hosts       (servers you trust)
~/.ssh/config            (your shortcuts)
  • Private key: stays on your machine. Never share it.

  • Public key: safe to share. You place it on every server you want to access.

  • known_hosts: remembers each server's fingerprint so SSH can warn you if a server changes unexpectedly.

  • config: a file where you define shortcuts so you can type ssh web instead of a long command.

1. Connecting

ssh [email protected]               # connect as a user to an IP or hostname
ssh -p 2222 user@host               # custom port (lowercase p)
ssh -i ~/.ssh/mykey user@host       # use a specific private key
ssh user@host 'uptime'              # run one command and return
ssh user@host 'df -h && free -h'    # run several commands
ssh -t user@host 'sudo systemctl status nginx'   # -t gives commands a terminal (needed for sudo prompts)
exit                                # close the session (or press Ctrl + D)

2. Creating and Installing Keys

Keys are safer and more convenient than passwords. Use the modern ed25519 type.

ssh-keygen -t ed25519 -C '[email protected]'       # generate a key pair
ssh-keygen -t ed25519 -f ~/.ssh/id_work -C 'work'   # choose a file name
ssh-copy-id user@host                            # install your public key on a server
ssh-copy-id -i ~/.ssh/id_work.pub user@host      # install a specific key
ssh-keygen -p -f ~/.ssh/id_ed25519               # change a key's passphrase
ssh-keygen -lf ~/.ssh/id_ed25519.pub             # show a key's fingerprint
cat ~/.ssh/id_ed25519.pub                        # print the public key (for GitHub, GitLab, etc.)

Always set a passphrase when prompted. If someone copies your key file, the passphrase is the last line of defense.

Required file permissions

SSH refuses to work if your key files are readable by others.

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519          # private key
chmod 644 ~/.ssh/id_ed25519.pub      # public key
chmod 600 ~/.ssh/authorized_keys     # on the server
chmod 600 ~/.ssh/config

3. ssh-agent: Type Your Passphrase Once

The agent holds your decrypted keys in memory for the session.

eval "$(ssh-agent -s)"                  # start the agent in this shell
ssh-add ~/.ssh/id_ed25519               # add a key (asks for the passphrase once)
ssh-add -l                              # list loaded keys
ssh-add -D                              # remove all keys from the agent
ssh-add --apple-use-keychain ~/.ssh/id_ed25519   # macOS: store the passphrase in Keychain

Many desktops start an agent for you. You can also add AddKeysToAgent yes to your config file (next section) so keys load automatically on first use.

4. The SSH Config File

This is the single biggest quality-of-life upgrade in SSH. Create or edit ~/.ssh/config:

Host web
    HostName 203.0.113.10
    User deploy
    Port 2222
    IdentityFile ~/.ssh/id_work
    IdentitiesOnly yes

Host bastion
    HostName bastion.example.com
    User ops

Host internal-db
    HostName 10.0.2.15
    User admin
    ProxyJump bastion

Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
    AddKeysToAgent yes

Now these work:

ssh web                 # instead of: ssh -p 2222 -i ~/.ssh/id_work [email protected]
ssh internal-db         # automatically hops through the bastion
scp report.pdf web:/tmp/   # config applies to scp, rsync, and Git too

Important: SSH uses the first matching value it finds, so put specific Host blocks first and the catch-all Host * last.

5. Transferring Files

scp: simple copying

scp file.txt user@host:/tmp/                 # upload a file
scp user@host:/var/log/app.log .             # download a file
scp -r folder/ user@host:/backup/            # copy a folder
scp -P 2222 file.txt user@host:/tmp/         # custom port (uppercase P for scp!)

rsync: smarter copying

rsync sends only what changed, resumes interrupted transfers, and is the better choice for anything large or repeated.

rsync -avz src/ user@host:/backup/               # sync a folder
rsync -avz --progress big.iso user@host:/tmp/    # show progress
rsync -avz -e 'ssh -p 2222' src/ user@host:/dest/    # custom SSH port
rsync -avz --dry-run src/ user@host:/dest/       # preview without changing anything

A trailing slash matters: src/ copies the contents of the folder, while src copies the folder itself. Be careful with --delete, which removes files on the destination that no longer exist in the source.

sftp: interactive transfers

sftp user@host
# inside the session:
ls                  # list remote files
lls                 # list local files
cd /var/www         # change remote directory
lcd ~/Downloads     # change local directory
get file.txt        # download
put file.txt        # upload
bye                 # quit

6. Port Forwarding (Tunnels)

Tunnels let you reach services that are not directly exposed, using SSH as an encrypted pipe. The three types confuse everyone at first, so here is a simple way to think about them.

Local forwarding (-L): bring a remote service to your machine

ssh -L 8080:localhost:80 user@server
# now http://localhost:8080 on your machine shows the server's port 80

The format is -L local_port:destination_host:destination_port. The destination is resolved from the server's point of view, which makes this powerful:

# Reach a database that only the server can see
ssh -L 5432:db.internal:5432 user@bastion
# then connect your local tools to localhost:5432

Remote forwarding (-R): expose your machine through the server

ssh -R 9000:localhost:3000 user@server
# port 9000 on the server now forwards to port 3000 on YOUR machine

By default the remote port only listens on the server's loopback interface. Making it public requires GatewayPorts in the server's config, so think carefully before doing that.

Dynamic forwarding (-D): a SOCKS proxy

ssh -D 1080 -N user@server
# set your browser or app to use SOCKS5 proxy localhost:1080

Running tunnels in the background

ssh -N -f -L 5432:localhost:5432 user@server    # -N: no remote command, -f: go to background
pkill -f 'ssh -N -f -L 5432'                    # stop it later

7. Jump Hosts (Bastions)

Many private servers are only reachable through a bastion host. Use ProxyJump instead of the older, riskier agent forwarding.

ssh -J [email protected] [email protected]           # one-off jump
ssh -J jump1,jump2 user@target                           # chain several hops
scp -J ops@bastion file.txt [email protected]:/tmp/        # works with scp too

For permanent shortcuts, set ProxyJump in your config file, as shown in section 4.

8. Keeping Connections Fast and Alive

Stop idle sessions from dropping

Add to ~/.ssh/config:

Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3

Reuse one connection for many commands (multiplexing)

This makes repeated ssh, scp, and git operations to the same host almost instant:

Host *
    ControlMaster auto
    ControlPath ~/.ssh/cm-%r@%h:%p
    ControlPersist 10m
ssh -O check web        # is the shared connection alive?
ssh -O exit web         # close it

Survive disconnects with tmux

If your Wi-Fi drops, a normal SSH session and everything running in it dies. Run long jobs inside tmux on the server:

ssh user@host
tmux new -s work        # start a named session
# ...run your long task, then detach with Ctrl + B, then D...
tmux attach -t work     # reattach after reconnecting

Escape a frozen session

If your terminal hangs, press Enter, then type ~ followed by . to force-disconnect. Type ~? for the list of escape sequences.

9. Hardening the Server

These settings live in /etc/ssh/sshd_config on the server.

PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers alice deploy
sudo sshd -t                       # test the config for syntax errors
sudo systemctl restart ssh         # Debian/Ubuntu (the service is called "sshd" on RHEL/Fedora)

Do this safely: before you disable password logins, confirm that key-based login works. Then keep your current session open while you test a second connection in a new terminal. If the new one fails, you can still fix the config from the first one. Many people lock themselves out by skipping this step.

Tools like fail2ban can also block repeated failed logins automatically.

10. Troubleshooting by Error Message

Permission denied (publickey) The server did not accept your key. Run ssh -v user@host and check which keys are offered. Confirm your public key is in the server's ~/.ssh/authorized_keys, that you are using the right username, and that file permissions are correct (section 2).

Connection refused Nothing is listening on that port. The SSH service may be stopped, the port may be different, or a firewall is rejecting you. On the server, check sudo systemctl status ssh.

Connection timed out Packets are being dropped, usually by a firewall or security group, or the IP is wrong. Verify the address and check cloud firewall rules.

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! The server's fingerprint no longer matches known_hosts. This can be harmless (the server was rebuilt) or a sign of interception. Confirm with whoever runs the server first, and only then remove the old entry:

ssh-keygen -R hostname-or-ip

Too many authentication failures Your agent is offering many keys, and the server gives up before reaching the right one. Force a single key:

ssh -o IdentitiesOnly=yes -i ~/.ssh/id_work user@host

WARNING: UNPROTECTED PRIVATE KEY FILE! Your key is readable by others. Fix it with chmod 600 ~/.ssh/id_ed25519.

Broken pipe or frequent drops Add ServerAliveInterval 60 to your config (section 8).

Test a Git host connection

ssh -T [email protected]

11. Handy One-Liners

# Run a local script on a remote machine without copying it
ssh user@host 'bash -s' < script.sh

# Compare a remote file with a local one
ssh user@host 'cat /etc/hosts' | diff - /etc/hosts

# Back up a folder to a remote machine over SSH
tar czf - folder/ | ssh user@host 'cat > backup.tgz'

# Download a remote folder as an archive without temp files
ssh user@host 'tar czf - /var/www' > www.tgz

# Mount a remote folder as if it were local (requires sshfs)
mkdir -p ~/remote && sshfs user@host:/var/www ~/remote
fusermount -u ~/remote          # unmount on Linux (use "umount ~/remote" on macOS)

# See which keys are loaded and their fingerprints
ssh-add -l

# Copy your public key to the clipboard (Linux with xclip)
xclip -sel clip < ~/.ssh/id_ed25519.pub

Safety Habits Worth Building

  1. Never share a private key. Only the .pub file ever leaves your machine.

  2. Use a passphrase and ed25519 keys. A stolen key without a passphrase is a stolen identity.

  3. Disable password login on servers once key login works, and disable root login.

  4. Verify the fingerprint on first connect when you can, rather than typing yes out of habit.

  5. Avoid StrictHostKeyChecking=no in anything beyond a throwaway test, since it switches off protection against interception.

  6. Prefer ProxyJump over agent forwarding (-A). A compromised intermediate server can misuse a forwarded agent.

  7. Remove old keys. Periodically review authorized_keys and delete keys for people or laptops that no longer need access.

  8. Keep an encrypted backup of your keys, so losing a laptop does not mean losing access everywhere.

Final Thoughts

You do not need to memorize everything here. Learn the daily basics of ssh, ssh-keygen, ssh-copy-id, and scp, then invest ten minutes in your ~/.ssh/config file, which pays you back every day. Keep the tunneling and troubleshooting sections nearby for the moments you need them.

Try one new thing this week: add a Host block for your most-used server, or set up a local tunnel to a service you normally reach another way. That is how a cheat sheet turns into real skill.

Comments0

Log in to join the discussion.

No comments yet.

Arpan Singh

Read articles by this author.

Subscribe to Arpan Singh's newsletter

Get the articles this author chooses to send by email.