ssh Command Cheat Sheet
ssh (Secure Shell) is the primary tool for securely connecting to remote systems over an encrypted network connection. It provides secure encrypted communications between two untrusted hosts over an insecure network and can forward X11 connections, arbitrary TCP ports, and Unix-domain sockets.
Synopsis
ssh [-46AaCfGgKkMNnqsTtVvXxYy] [options] [user@]hostname [command]
Description
SSH is a protocol and program for logging into a remote machine and executing commands on a remote machine. It is intended to replace rlogin and rsh, and provide secure encrypted communications between two untrusted hosts over an insecure network.
X11 connections, arbitrary TCP ports, and Unix-domain sockets can also be forwarded over the secure channel.
Basic Usage
Simple Remote Login
Connect to a remote server with your current username:
ssh hostname
Login as Different User
ssh user@hostname
ssh -l user hostname
Execute Remote Command
ssh user@hostname 'ls -la /var/log'
Execute Multiple Commands
ssh user@hostname 'uptime; df -h; whoami'
Common Options
-p PORT
Specify custom SSH port (default is 22).
ssh -p 2222 user@hostname
-i IDENTITY_FILE
Specify SSH private key file.
ssh -i ~/.ssh/id_rsa user@hostname
ssh -i /path/to/private_key user@hostname
-4, -6
Force IPv4 or IPv6 only.
ssh -4 user@hostname # Force IPv4
ssh -6 user@hostname # Force IPv6
-v, -vv, -vvv
Verbose mode for debugging (multiple v's increase verbosity).
ssh -v user@hostname # Basic debug info
ssh -vv user@hostname # More detailed
ssh -vvv user@hostname # Maximum verbosity
-q
Quiet mode - suppresses warning and diagnostic messages.
ssh -q user@hostname
-C
Enable compression (useful for slow connections).
ssh -C user@hostname
-N
Do not execute remote command - useful for port forwarding only.
ssh -N -L 8080:localhost:80 user@hostname
-f
Go to background before command execution.
ssh -f user@hostname command
-T
Disable pseudo-terminal allocation.
ssh -T user@hostname 'backup-script.sh'
-t
Force pseudo-terminal allocation (useful for interactive programs).
ssh -t user@hostname 'sudo command'
ssh -t ssh-gateway ssh internal-server # Nested SSH
Authentication
Password Authentication
ssh user@hostname
# Enter password when prompted
Key-Based Authentication
Generate SSH key pair:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
ssh-keygen -t ed25519 -C "your_email@example.com" # Modern, recommended
Copy public key to server:
ssh-copy-id user@hostname
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@hostname
Manual key installation:
cat ~/.ssh/id_rsa.pub | ssh user@hostname 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys'
Using SSH Agent
# Start SSH agent
eval "$(ssh-agent -s)"
# Add key to agent
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_ed25519
# List loaded keys
ssh-add -l
# Remove all keys from agent
ssh-add -D
-A: Forward Authentication Agent
ssh -A user@jumphost
# Now can SSH from jumphost to other servers using local keys
Port Forwarding (Tunneling)
Local Port Forwarding (-L)
Forward local port to remote destination:
# Syntax: -L local_port:destination:destination_port
ssh -L 8080:localhost:80 user@hostname
Use case: Access remote web server on your local port 8080:
ssh -L 8080:localhost:80 user@webserver
# Now access: http://localhost:8080
Database access:
ssh -L 3306:localhost:3306 user@db-server
# Connect local MySQL client to localhost:3306
Multiple port forwards:
ssh -L 8080:localhost:80 -L 3306:localhost:3306 user@server
Remote Port Forwarding (-R)
Forward remote port to local machine:
# Syntax: -R remote_port:destination:destination_port
ssh -R 8080:localhost:80 user@hostname
Use case: Expose local web server to remote server:
ssh -R 8080:localhost:3000 user@remote-server
# Remote server can access your local app on port 8080
Dynamic Port Forwarding (-D) - SOCKS Proxy
Create a SOCKS proxy:
ssh -D 1080 user@hostname
Configure browser to use SOCKS5 proxy localhost:1080:
# Firefox/Chrome -> Settings -> Network -> SOCKS Host: localhost, Port: 1080
Command line usage with SOCKS:
ssh -D 1080 -N user@server &
curl --socks5 localhost:1080 http://example.com
-w: VPN Tunneling
ssh -w 0:0 user@hostname
Jump Hosts (ProxyJump)
-J: Jump through intermediate host
ssh -J jumphost user@internal-server
ssh -J user1@jump1,user2@jump2 user@final-destination
Multiple hops:
ssh -J bastion1,bastion2,bastion3 user@target
With different ports:
ssh -J user@jump:2222 user@server
Configuration File
~/.ssh/config
Create persistent connection settings:
# Default settings for all hosts
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
Compression yes
# Specific host configuration
Host myserver
HostName example.com
User username
Port 22
IdentityFile ~/.ssh/id_rsa
ForwardAgent yes
# Jump host configuration
Host internal
HostName 192.168.1.100
User admin
ProxyJump bastion
Host bastion
HostName bastion.example.com
User jump_user
Port 2222
# Short alias
Host db
HostName database.company.com
User dbadmin
LocalForward 3306 localhost:3306
# Wildcard configuration
Host *.company.com
User company_user
IdentityFile ~/.ssh/company_key
Connect using alias:
ssh myserver
ssh internal
ssh db
Common Config Options
Host <alias>
HostName <actual_hostname_or_ip>
User <username>
Port <port_number>
IdentityFile <path_to_private_key>
ForwardAgent <yes|no>
ProxyJump <jump_host>
LocalForward <local_port> <remote_host>:<remote_port>
RemoteForward <remote_port> <local_host>:<local_port>
DynamicForward <local_port>
ServerAliveInterval <seconds>
ServerAliveCountMax <count>
Compression <yes|no>
StrictHostKeyChecking <yes|no|ask>
UserKnownHostsFile <path>
LogLevel <QUIET|FATAL|ERROR|INFO|VERBOSE|DEBUG>
Connection Multiplexing
Share multiple sessions over single network connection:
Config file setup:
Host *
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%h:%p
ControlPersist 10m
Create socket directory:
mkdir -p ~/.ssh/sockets
Benefits: - Faster subsequent connections - Reuses authentication - Reduces server load
Control master manually:
# Start master connection
ssh -M -S /tmp/ssh-socket user@hostname
# Use existing connection
ssh -S /tmp/ssh-socket user@hostname
# Check connection status
ssh -S /tmp/ssh-socket -O check user@hostname
# Close connection
ssh -S /tmp/ssh-socket -O exit user@hostname
X11 Forwarding
-X: Enable X11 forwarding
ssh -X user@hostname
xclock # Run GUI app on remote, display locally
-Y: Trusted X11 forwarding
ssh -Y user@hostname
firefox # Run remote Firefox, display locally
Config file:
Host remote
HostName example.com
ForwardX11 yes
ForwardX11Trusted yes
File Transfer
Using SSH for SCP-like transfer
# Copy file to remote
scp file.txt user@hostname:/remote/path/
# Copy from remote
scp user@hostname:/remote/file.txt /local/path/
# Recursive directory
scp -r directory/ user@hostname:/remote/path/
Using tar over SSH
# Send directory
tar czf - directory/ | ssh user@hostname 'tar xzf - -C /destination/'
# Receive directory
ssh user@hostname 'tar czf - /remote/directory/' | tar xzf -
Security Best Practices
Disable Password Authentication
Server-side /etc/ssh/sshd_config:
PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin no
Use Strong Key Types
# Ed25519 (recommended)
ssh-keygen -t ed25519 -a 100
# RSA 4096-bit
ssh-keygen -t rsa -b 4096 -a 100
Protect Private Keys
chmod 600 ~/.ssh/id_rsa
chmod 700 ~/.ssh
Use Passphrase-Protected Keys
ssh-keygen -t ed25519
# Enter passphrase when prompted
Known Hosts Management
# Remove specific host
ssh-keygen -R hostname
# Hash known_hosts file
ssh-keygen -H -f ~/.ssh/known_hosts
Advanced Examples
Reverse Tunnel (Expose Local Service)
# Expose local port 3000 on remote port 8080
ssh -R 8080:localhost:3000 user@server
Persistent Tunnel with Autossh
autossh -M 0 -f -N -L 8080:localhost:80 user@hostname
SSH Over Specific Interface
ssh -B eth0 user@hostname
Execute Local Script on Remote
ssh user@hostname 'bash -s' < local_script.sh
Copy SSH Key Without ssh-copy-id
cat ~/.ssh/id_rsa.pub | ssh user@host 'cat >> ~/.ssh/authorized_keys'
SSH with Timeout
ssh -o ConnectTimeout=10 user@hostname
Disable Host Key Checking (Testing Only!)
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null user@host
Keep Connection Alive
ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 user@hostname
SSH Through HTTP Proxy
ssh -o ProxyCommand='nc -X connect -x proxy:8080 %h %p' user@hostname
Mount Remote Filesystem (SSHFS)
sshfs user@hostname:/remote/path /local/mount/point
fusermount -u /local/mount/point # Unmount
Port Knocking
knock server 7000 8000 9000 && ssh user@server
Emergency Disconnect
Press ~. (tilde + period) on new line to force disconnect.
Other escape sequences:
- ~? - Help
- ~# - List forwarded connections
- ~& - Background SSH
- ~^Z - Suspend SSH
Troubleshooting
Connection Timeout
# Increase timeout
ssh -o ConnectTimeout=30 user@hostname
# Keep connection alive
ssh -o ServerAliveInterval=60 user@hostname
Permission Denied (publickey)
# Debug authentication
ssh -vvv user@hostname
# Check permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 644 ~/.ssh/authorized_keys
Too Many Authentication Failures
# Specify single key
ssh -o IdentitiesOnly=yes -i ~/.ssh/specific_key user@hostname
Broken Pipe / Connection Reset
# Add to ~/.ssh/config
Host *
ServerAliveInterval 60
ServerAliveCountMax 120
TCPKeepAlive yes
Exit Status
| Code | Meaning |
|---|---|
| 0 | Success |
| 1-254 | Exit status from remote command |
| 255 | SSH error (connection failed, authentication failed, etc.) |
Common Use Cases
Daily Remote Work
# Connect to work server
ssh work
# Run screen/tmux session
ssh -t work screen -rd
Backup Over SSH
tar czf - /data | ssh backup-server 'cat > backup-$(date +%F).tar.gz'
Database Management
# Forward database port
ssh -L 5432:localhost:5432 db-server
# Now connect with local client
psql -h localhost -U dbuser database
Web Development
# Forward multiple ports
ssh -L 3000:localhost:3000 -L 8080:localhost:8080 dev-server
Tips
- Use SSH keys instead of passwords for better security
- Use SSH config file for frequently accessed hosts
- Enable connection multiplexing for faster connections
- Use compression (
-C) on slow networks - Keep connections alive with
ServerAliveInterval - Use ProxyJump instead of multiple SSH commands
- Protect private keys with proper permissions (600)
- Use Ed25519 keys for best security and performance
- Disable root login on servers
- Use fail2ban or similar tools to prevent brute force attacks