logo

My ssh cheatsheet

ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network.

SSH is commonly used for:

  • Secure remote server management
  • File transfers
  • Tunneling and port forwarding
  • Deployment and automation

Basic SSH commands

Connect to a remote server:

bash
ssh username@remote_host

Use a specific identity (private key):

bash
ssh -i path/to/key_file username@remote_host

Use a specific port:

bash
ssh username@remote_host -p 2222

Run a command remotely:

bash
ssh remote_host command -with -flags

Advanced SSH usage

Dynamic port forwarding (SOCKS proxy on localhost:9999):

bash
ssh -D 9999 -C username@remote_host

SSH jumping: Connect through a jumphost (multiple hops separated by commas):

bash
ssh -J username@jump_host username@remote_host

Public key authentication

Local system has a cryptographic key pair - public key and private key. The server is configured to recognize the public key by adding it to ~/.ssh/authorized_keys. Anyone that has the corresponding private key will be granted access to the server.

How to set up public key authentication

  1. Generate a key pair:
    bash
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    
  2. Copy your public key to the server (ssh-copy-id must be installed on your local machine):
    bash
    ssh-copy-id username@remote_host
    
  3. In a separate terminal, connect with ssh -i ~/.ssh/id_rsa username@remote_host (substitute the key you generated). Confirm that you reach the intended account using the key. A key passphrase prompt unlocks the local key. It is different from the remote account password. Keep your existing session open while checking a new login method.

Security tip: Never share your private key. Keep it secure and consider using a passphrase.

Client config setting

Instead of annoyingly typing

bash
ssh root@203.0.113.10 -p 2333

We can actually set the ssh config in ~/.ssh/config with

bash
Host remoteServer           # host name alias that is easy to memorize
HostName 203.0.113.10     # host ip or host name
User root                   # user
Port 2333                   # port
IdentityFile ~/.ssh/id_rsa  # private key location

Then we can do the equivalent with easy typing:

bash
ssh remoteServer

References