SSH cheatsheet
On this page 6 sections
Sure! Here's a comprehensive SSH (Secure Shell) cheat sheet, covering basic to advanced features, along with tips and examples:
Basic SSH Usage
-
Connect to a Host
ssh user@hostnameConnect to
hostnameasuser. -
Connect with a Specific Port
ssh -p 2222 user@hostnameConnect to
hostnameon port2222. -
SSH Key Generation
ssh-keygenGenerate a new SSH key pair.
-
Copy SSH Key to a Host
ssh-copy-id user@hostnameCopy your local public key to the remote host for key-based authentication.
File Transfer
-
SCP: Copy Files Over SSH
scp localfile.txt user@hostname:/remote/path scp user@hostname:/remote/path/remotefile.txt localfile.txtCopy
localfile.txtto a remote host, or copy a file from a remote host to local. -
RSync Over SSH
rsync -avz -e ssh localfile.txt user@hostname:/remote/pathSecurely sync files over SSH.
Advanced SSH Features
-
SSH Tunneling (Port Forwarding)
-
Local Port Forwarding
ssh -L localPort:remoteAddress:remotePort user@hostnameForward a local port to a remote address and port.
-
Remote Port Forwarding
ssh -R remotePort:localAddress:localPort user@hostnameForward a remote port to a local address and port.
-
Dynamic Port Forwarding (SOCKS Proxy)
ssh -D localPort user@hostnameCreate a SOCKS proxy on a local port.
-
-
SSH Config File
- Create a
~/.ssh/configfile for easier connection management. Example:Host myserver HostName server.example.com User myuser Port 2222 IdentityFile ~/.ssh/mykey - Connect using the alias:
ssh myserver
- Create a
-
SSH Agent Forwarding
ssh -A user@hostnameForward your SSH key agent to the host (useful for hopping between hosts).
-
X11 Forwarding
ssh -X user@hostnameForward X11 (GUI) applications from the remote host.
SSH Tips
-
Keep SSH Sessions Alive
- Add the following to
~/.ssh/config:Host * ServerAliveInterval 60 - This sends a keepalive signal every 60 seconds to keep the connection active.
- Add the following to
-
Use SSH Multiplexing
- Reuse an existing SSH connection for multiple sessions to the same host.
- Add to
~/.ssh/config:Host * ControlMaster auto ControlPath ~/.ssh/sockets/%r@%h-%p ControlPersist 600
-
Mount Remote Filesystem with SSHFS
sshfs user@hostname:/remote/path /local/mount/pointMount a remote filesystem locally via SSHFS.
Security Tips
-
Disable Root Login
- In the remote
/etc/ssh/sshd_configfile, ensure:PermitRootLogin no
- In the remote
-
Use Key-Based Authentication
- Disable password authentication in
/etc/ssh/sshd_config:PasswordAuthentication no
- Disable password authentication in
-
Change Default SSH Port
- In
/etc/ssh/sshd_config:Port 2222
- In
Examples
-
Connect to a Server
ssh [email protected] -
Securely Transfer a File
scp report.txt [email protected]:/home/myuser/ -
SSH Tunnel to Access a Remote Database Locally
ssh -L 3306:localhost:3306 myuser@dbserverAccess a remote MySQL server on local port
3306.