3

The SSH Commands Cheat Sheet You’ll Regret Missing Out On

 10 months ago
source link: https://www.stationx.net/ssh-commands-cheat-sheet/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The SSH Commands Cheat Sheet You’ll Regret Missing Out On

May 17, 2023 / By Cassandra Lee
The SSH Commands Cheat Sheet You’ll Regret Missing Out On

Whether you need a quick recap of SSH commands or you’re learning SSH from scratch, nothing beats a handy guide. It’s easy to get overwhelmed knowing what SSH or OpenSSH commands are important enough for your current task. SSH is necessary for network administrators and anyone who needs to log in to remote computers and servers.

The good news is: we’ve brought you a neat, no-nonsense SSH cheat sheet suitable for beginners and advanced users. It covers basic SSH commands, SSH configurations and options, remote server management, advanced SSH commands, and tunneling, including using a router and Wireshark to capture web traffic on a remote host.

Download our SSH commands cheat sheet here. When you’re ready, let’s dive in.

What Is SSH?

SSH (short for “Secure Shell” or “Secure Socket Shell”) is a network protocol for accessing network services securely over unsecured networks. It includes the suite of utilities implementing it, such as:

  • ssh-keygen: for creating new authentication key pairs for SSH;
  • SCP (Secure Copy Protocol): for copying files between hosts on a network;
  • SFTP (Secure File Transfer Protocol): for sending and receiving files. It’s an SSH-secured version of FTP (File Transfer Protocol), and it has replaced FTP and FTPS (FTP Secure) as the preferred mechanism for file sharing over the Internet.

An SSH server, by default, listens for connections on the standard Transmission Control Protocol (TCP) port 22. Your applications may listen for SSH connections on other ports.

SSH lets you securely manage remote systems and applications, such as logging in to another computer over a network, executing commands, and moving files from one computer to another. An advanced SSH functionality is the creation of secure tunnels to run other application protocols remotely.

SSH Cheat Sheet Search

Search our SSH cheat sheet to find the right cheat for the term you're looking for. Simply enter the term in the search bar, and you'll receive the matching cheats available.

Basic SSH Commands

The following are fundamental SSH commands. Commit as many to memory as you can.

CommandDescription
sshConnect to a remote server
ssh pi@raspberryConnect to the device raspberry on the default SSH port 22 as user pi
ssh pi@raspberry -p 3344Connect to the device raspberry on a specific port 3344 as user pi
ssh -i /path/file.pem [email protected]Connect to [email protected] via the key file /path/file.pem as user admin
ssh [email protected] 'ls -l'Execute remote command ls -l on 192.168.2.2 as user root
$ ssh [email protected] bash < script.shInvoke the script script.sh in the current working directory spawning the SSH session to 192.168.3.3 as user user
ssh [email protected] "tar cvzf - ~/ffmpeg" > output.tgzCompress the ~/ffmpeg directory and download it from a server Best.local as user friend
ssh-keygenGenerate SSH keys (follow the prompts)
ssh-keygen -F [ip/hostname]Search for some IP address or hostname from ~/.ssh/known_hosts (logged-in host)
ssh-keygen -R [ip/hostname]Remove some IP address or hostname from ~/.ssh/known_hosts (logged-in host)
ssh-keygen -f ~/.ssh/filenameSpecify file name
ssh-keygen -y -f private.key > public.pubGenerate public key from private key
ssh-keygen -c -f ~/.ssh/id_rsaChange the comment of the key file ~/.ssh/id_rsa
ssh-keygen -p -f ~/.ssh/id_rsaChange passphrase of private key ~/.ssh/id_rsa
ssh-keygen -t rsa -b 4096 -C "[email protected]"Generate an RSA 4096-bit key with “[email protected]” as a comment:
-t: Type of key (rsa, ed25519, dsa, ecdsa)
-b: The number of bits in the key
-C: Provides a new comment
scpCopy files securely between servers
scp user@server:/folder/file.ext dest/Copy from remote to local destination dest/
scp dest/file.ext user@server:/folderCopy from local to remote
scp user1@server1:/file.ext user2@server2:/folderCopy between two different servers
scp user@server:/folder/* .Copies from a server folder to the current folder on the local machine
scp -rRecursively copy entire directories
scp -r user@server:/folder dest/Copy the entire folder to the local destination dest/
scp user@server:/folder/* dest/Copy all files from a folder to the local destination dest/
scp -COption to compress data
scp -vOption to print verbose info
scp -pOption to preserve the last modification timestamps of the transferred files
scp -P 8080Option to connect to remote host port 8080
scp -BOption for batch mode and prevent you from entering passwords or passphrases
sftpSecurely transfer files between servers
sftp -pOption to preserve the last modification timestamps of the transferred files
sftp -P 8080Option to connect to remote host port 8080
sftp -rRecursively copy entire directories when uploading and downloading. SFTP doesn’t follow symbolic links encountered in the tree traversal.

SSH Configurations and Options

Have you ever wondered how SSH remembers your login credentials for various machines? This section is a brief reference on how to do so.

CommandDescription
man ssh_configOpen OpenSSH SSH client configuration files. This manual lists all the OpenSSH parameters you can change.
cat /etc/ssh/ssh_config | lessView your OpenSSH client system-wide configuration file
cat /etc/ssh/sshd_config | lessView your OpenSSH server system-wide configuration file; the “d” stands for the server “daemon”
cat ~/.ssh/config | lessView your SSH client user-specific configuration file
cat ~/.ssh/id_{type} | lessView your SSH client private key; type is any of rsa, ed25519, dsa, ecdsa.
cat ~/.ssh/id_{type}.pub | lessView your SSH client public key; type is any of rsa, ed25519, dsa, ecdsa.
cat ~/.ssh/known_hosts | lessView your SSH client logged-in hosts
cat ~/.ssh/authorized_keys | lessView your SSH client authorized login keys
ssh-agentHold private SSH keys used for public key authentication (RSA, DSA, ECDSA, Ed25519)
ssh-agent -E fingerprint_hash              Specify the hash algorithm used when displaying key fingerprints.
Valid fingerprint_hash options are sha256 (default) and md5.
ssh-agent -t lifetimeSet up a maximum lifetime for identities/private keys, overwritable by the same setting in ssh-add
Examples of lifetime:
600 = 600 seconds (10 minutes)
23m = 23 minutes
1h45 = 1 hour 45 minutes
ssh-addAdd SSH keys to the ssh-agent
ssh-add -lList your private keys cached by ssh-agent
ssh-add -t lifetimeSet up a maximum lifetime for identities/private keys.
Examples of lifetime:
600 = 600 seconds (10 minutes)
23m = 23 minutes
1h45 = 1 hour 45 minutes
ssh-add -LList the public key parameters of all saved identities
ssh-add -DDelete all cached private keys
ssh-copy-idCopy, install, and configure SSH keys on a remote server
ssh-copy-id user@serverCopy SSH keys to a server as a user
ssh-copy-id server1Copy to some alias server server1 with the default login
ssh-copy-id -i ~/.ssh/id_rsa.pub user@serverCopy a specific key to a server as a user

Remote Server Management

The operating systems of SSH servers are mostly Unix/Linux, so once you’ve logged in to a server via SSH, the following commands are largely the same as their counterparts in Unix/Linux. Check out our Unix commands cheat sheet and Linux command line cheat sheet for other file management commands applicable to SSH.

CommandDescription
cdChange the current working directory
killStop a running process
lsList files and directories
mkdirCreate a new directory
mvMove files or directories
nanoEdit a file in the terminal using Nano
psList running processes
pwdDisplay the current working directory
tailView the last few (10, by default) lines of a file
topMonitor system resources and processes
touchCreate a new file or update the timestamp of an existing file
vimEdit a file in the terminal using Vim
exitClose the SSH session

Using PowerShell to access a lab account on a network computer via SSH on Windows 10

Advanced SSH Commands

This table lists some complex SSH utilities that can help with network administration tasks: SSH File System (SSHFS), data compression, and X11 forwarding.

To conduct X11 forwarding over SSH, do these three things:

  1. Set up your client (~/.ssh/config) to forward X11 by setting these parameters:
    Host *
    ForwardAgent yes
    ForwardX11 yes
  2. Set up your server (/etc/ssh/sshd_config) to allow X11 by setting these parameters:
    X11Forwarding yes
    X11DisplayOffset 10
    X11UseLocalhost no
  3. Set up X11 authentication on your server by installing xauth.
CommandDescription
sshfsMount a remote server’s file system on a local directory.
Remember to install this program onto your machine before use. Example installation commands:
• sudo apt install sshfs # Ubuntu/Debian
• sudo yum install fuse-sshfs # CentOS

Learn to install apps on various Linux distributions here.
ssh -C hostnameCompress SSH traffic to improve performance on slow connections.
Alternatively, insert Compression yes into your SSH configuration files.
ssh -o "Compression yes" -v hostnameAn alternative method to compress SSH traffic to improve performance on slow connections.
This is the same as inserting Compression yes into your SSH configuration files.
ssh -X user@serverEnable X11 forwarding over SSH: forward graphical applications from a remote server as a user to a local machine.
ssh -o ForwardX11=yes user@serverEnable X11 forwarding over SSH: forward graphical applications from a remote server as a user to a local machine.
ssh -xDisable X11 forwarding
ssh -YEnable trusted X11 forwarding. This option is riskier than ssh -X as it forwards the entire display of the SSH server to the client.

Tunneling

These SSH command line options create secure tunnels.

OptionsDescriptionSyntax / Example
-LLocal port forwarding: forward a port on the local machine (SSH client) to a port on the remote machine (ssh_server as user), the traffic of which goes to a port on the destination machine.
The parameters local_port and remote_port can match.
ssh user@ssh_server -L local_port:destination:remote_port
# Examplessh [email protected] -L 2222:10.0.1.5:3333
-JProxyJump; ensure that traffic passing through the intermediate/bastion hosts is always encrypted end-to-end.
ProxyJump is how you use bastion hosts to connect to a remote host with a single command.
ssh -J proxy_host1 remote_host2
ssh -J user@proxy_host1 user@remote_host2
# Multiple bastion hosts/jumpsssh -J user@proxy_host1:port1,user@proxy_host2:port2 user@remote_host3
-RRemote port forwarding: forward a port remote_port on the remote machine (ssh_server as user) to a port on the local machine (SSH client), the traffic of which goes to a port destination_port on the destination machine.
An empty remote means the remote SSH server will bind on all interfaces.
Additional SSH options in the example:
-N: don’t execute remote commands; useful for dedicated port forwarding
-f: run SSH in the background.
ssh -R [remote:]remote_port:destination:destination_port [user@]ssh_server
# Examplessh -R 8080:192.168.3.8:3030 -N -f [email protected]
-DSet up a SOCKS Proxy to tunnel traffic from a remote_host on which you’re the user to a local_port_number.
Additional SSH options in the example:
-q: quiet mode; don’t output anything locally
-C: compress data in the tunnel, save bandwidth
-N: don’t execute remote commands; useful for dedicated port forwarding
-f: run SSH in the background.
ssh -D local_port_number user@remote_host
# Examplessh -D 6677 -q -C -N -f [email protected]

SSH Tunneling Demonstration

Let’s show you two ways to pipe traffic from your router into Wireshark and monitor your network activity. The first demonstration involves installing programs onto a system used as a router; the second, without.

Using Django

As a demonstration, we’re piping traffic from a router into Wireshark, so that we can monitor live web traffic through an SSH tunnel. (The router below is a macOS computer hosting a Kali Linux virtual machine using the Wireshark instance installed on the latter.)

The setup is as follows:

  1. On the router: Enable remote access via SSH. (NOTE: On the macOS system, go to System Preferences > Sharing > turn on Remote Login and note the login username and hostname. For your router setup, check your specific manufacturer's guide to enable remote access via SSH.)
  2. On the router: Install Python Django and start up the Django template server on http://127.0.0.1:8000 using the Terminal command string django-admin startproject mysite; cd mysite; python manage.py runserver (or python3 manage.py runserver). Note the Django web app uses port 8000.
  3. On Kali Linux: execute this command to listen on port 8080: ls | nc -l -p 8080
  4. On Kali Linux: execute this command in a different Terminal tab/window. Below, 8000 is the router’s Django port, 8080 is the Kali Linux listening port on localhost, and the command involves remote port forwarding (-R): sudo ssh -R 8000:localhost:8080 user@router_ip
  5. On Kali Linux: start Wireshark and select the loopback interface (lo) as the capture device. Wireshark should be sniffing packets on lo now.
  6. On the router: visit http://127.0.0.1:8000 in a web browser. (Note localhost and 127.0.0.1 are equivalent.) The Django server wouldn’t load; it freezes instead because of the rerouted traffic.
  7. On Kali Linux: You should expect the following results:

Piping traffic of Django web app http://127.0.0.1:8000 on the macOS router into the Wireshark instance on Kali Linux

Wireshark HTTP packet corresponding to the Django web app on the router

Using tcpdump

The following is an alternative method for capturing remote web traffic passing through a router.

In Kali Linux, you’ll log in to your router via SSH, capture packets with the command-line packet capturing tool tcpdump, and pipe the traffic into Wireshark.

Here is the required command with the option flags explained:

ssh [username]@[hostname/ip] tcpdump -U -s 65525 -w - 'not port 22' | wireshark -k -i -

  • -U: No buffering. Produce real-time output.
  • -s 65525: Grab 65525 bytes of data from each packet rather than the default of 262144 bytes. 65525 is the maximum transmission unit of a Point-to-Point Protocol packet that Wireshark can handle. Adjust this number as you see fit.
  • -w: Write each packet to the output packet capture file on your local disk in Kali Linux. Combining -U and -w means tcpdump writes to your output file as the packets pour in, rather than until the memory buffer fills up.
  • 'not port 22': This is to prevent tcpdump from echoing the SSH packets sent between your machine and the router.
  • -k -i -: Start the capture immediately and use the command before the pipe character (|) as the capture interface.

Example of piping router traffic to Wireshark via tcpdump

After executing the command above, Wireshark opens:

Wireshark triggered

Next, the SSH client will prompt you to input your router password. Pasting it suffices:

SSH login successful. Now, tcpdump packet capture begins:

Meanwhile, Wireshark receives the piped traffic from tcpdump:

That’s it.

Conclusion

We have covered SSH, SCP, SFTP, SSH configuration commands such as ssh-agent, ssh-add, and ssh-copy-id, and various SSH tunneling commands.

Here are some tips for using SSH more efficiently and securely:

  • Disable X11 and TCP forwarding because attackers can use such weaknesses to access other systems on your network. Change the options on sshd_config to be AllowTcpForwarding no and X11Forwarding no.
  • Change the default options on sshd_config, such as changing the default port from 22 to another number.
  • Authenticate clients using SSH certificates created with ssh-keygen.
  • Use a bastion host with the help of tunneling commands.
  • Restrict SSH logins to specific IPs, such as adding user filtering with the AllowUsers option in sshd_config.

Thanks to its security measures and the ubiquity of networking tasks, SSH is indispensable for computer data communications. Hence every student and professional in IT and cyber security needs a working knowledge of SSH commands, and we hope this SSH cheat sheet is a good starter or refresher for you.

To learn more about SSH and secure network administration, check out the following courses from us:

How to connect to a server with SSH:
What port is SSH?
What is the use of PuTTY?
Is SSH only available for Unix systems?
Does SSH use TCP or UDP?

Level Up in Cyber Security: Join VIP Membership Today!

  • Cassandra is a writer, artist, musician, and technologist who makes connections across disciplines: cyber security, writing/journalism, art/design, music, mathematics, technology, education, psychology, and more. She's been a vocal advocate for girls and women in STEM since the 2010s, having written for Huffington Post, International Mathematical Olympiad 2016, and Ada Lovelace Day, and she's honored to join StationX. You can find Cassandra on LinkedIn and Linktree.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK