Akhilesh Yadav Being a Software Engineer, I love documenting my journey and share my learnings with other developers. I have passion for exploring Javascript, AWS Cloud and lot many things.
  1. Home
  2. /
  3. linux
  4. /
  5. SSH Command Cheatsheet to...

SSH Command Cheatsheet to become Linux Advance Pro User

7 min read

SSH Command Cheatsheet to become Linux Advance Pro User

Being in a Programming career, SSH is a widely known term and some like to call it as “Secure Shell” or “Secure Socket Shell”. SSH is a network protocol and it lets one to connect to different computer/server existing over an unsecured network (Internet or LAN) in a totally secured way. ssh is also a terminal program that connects to a server using an encrypted connection. This is useful when you do not have access to the required system directly and then you can connect to the required server system over internet if the SSH Port 22 is open on the Server System.

SSH can also be known as a cryptographic network protocol that transfer encrypted data over unsecured network. You can connect to the Remote Server Machine with user/password credential or through a public/private key authentication mechanism. It uses Client-Server Model where your local machine will be a Secure Shell Client application(like bash terminals or other GUI application) and Remote Server Machine will be a SSH-Server where session would run. SSH Server on your Remote Server Machine normally uses or listens on standard Transmission Control Protocol (TCP) port 22. It is an application layer protocol which resides at the 7th layer of the OSI Model. SSH was designed as a replacement for Telnet, which is also an application layer protocol that transferred data without encryption and in plain text which was sufficient for any middle-man/hacker to capture confidential data from live traffic.

Practical Use Cases of SSH includes:

  1. Accessing resources in the remote server
  2. Executing bash commands in the remote server, modifying files or doing any command-line operations.
  3. Transferring files between 2 different machine.
  4. Managing running application on the remote server.
  5. Patching/Upgrading the remote server machine.
  6. Accessing resources of Server Machine on local installed application. e.g. Database, File System, Remote Application
  7. Using as a Jump Box to access other server inside the private network.
  8. SSH can also be used to create secure tunnels for other application protocols, for example, to securely run X Window System graphical sessions remotely.
  9. Live piping output from remote machine to other machine.

Secure Shell has 2 ways of authentication which includes strong password authentication and public key authentication.

Key based authentication comes in 2 pair:

Public key – Used with encryption function of Secure Shell. No need to protect it. This will be used by your SSH Remote Server for encryption connection to client.
Private key – Used for decryption function of Secure Shell. This must be protected as its a private and would be used by your SSH Client for connecting to remote SSH Server.

If you deal with aws cloud/azure/gcp or virtual machine or docker container, then you might be familiar with using Putty graphical tool or SSH on linux or windows to perform some task on remote server using command-line console.  There are quite many tricks to use ssh in most clever way. SSH can move contents securely, provides different authentication mechanism, mount a filesystem using sshfs, port forwarding and reverse port forwarding, or use it as a proxy to access another private resource. There are many and we many not be able to cover all of them. But we will try to compile a list of all useful ssh usecases.

SSH Basics

  1. scp : Transfer files over ssh
  2. sftp : Active Terminal FTP session to download or upload files over network.
  3. ssh-keygen : Generate pair of public private key for your host.
  4. ssh-copy-id : Transfer local public key to other remote system.
  5. You can configure SSH presets related to different host in the ~/.ssh/config file. For example, suppose you want to connect to one of your server, you can set alias name for it and specify other details like port, username, identityFile, etc.
    Host ftpsever
      HostName mih0me.dyndns.org
      Port 1234
      User TheAl
      IdentityFile ~/.ssh/home_id
      ForwardX11 yes
      Compression yes
      TCPKeepAlive yes
  6. You can control if you want to use single TCP socket or multiple socket for multiple session to same server host. This way you can connect to remote host efficiently. Specify below lines in ~/.ssh/config file.
    ControlMaster auto 
    ControlPath ~/.ssh/master-%r@%h:%p

    To set it for all hosts, use the Host * line in the config file.

    You can add -S none  within ssh command to override the global setting and avoid usage of ControlMaster incase you have a lot of data over multiple connections
  7.  If you have multiple SSH Connection open and try to close the first ssh session, then it may hang if you try to exit it before all the other connections are close
      • To cause the original session to go to the background indefinitely, set below entry in ~/.ssh/config file.
      ControlPersist yes
      • If you want a little grace period you can set ControlPersist to a number like 180. That would cause the background session to end if there are no connections for three minutes. Set below entry in  ~/.ssh/config file.
      1. ControlPersist 180
  8. set TCPKeepAlive to yes if you need the server and client to test their connection & remain active during idle periods. And so iff the connection becomes idle, you won’t get disconnected.
  1. TCPKeepAlive yes

     

You can run below SSH commands on terminal or use it inside a bash script.

 

List of Popular Useful SSH Commands

Connect to SSH with password authentication
ssh username@IPAddress
Connect to SSH with private key authentication
ssh -i pathtoPrivateKey.pem <username>@<ssh_host>
Copy ssh key for SSH passwordless login
ssh-copy-id <username>@<ssh_host>

Or manually update ~/.ssh/authorized_keys on ssh host server

Copy your ssh public key to a server from a machine that doesn’t have ssh-copy-id. Pipe file output to remote.
cat ~/.ssh/id_rsa.pub | <username>@<ssh_host> "mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys"
Transfer SSH public key to another machine in one step
ssh-keygen; ssh-copy-id <username>@<ssh_host>; ssh <username>@<ssh_host>
Run ssh command
ssh <username>@<ssh_host> <commandHere>
Restart sshd server after /etc/ssh/sshd_config file modification
service sshd restart,  systemctl reload sshd.service
SSH with verbose ouptut
ssh -v <username>@<ssh_host>
Generate SSH Keys
ssh-keygen
Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the local side.
ssh -R 9000:localhost:9000 <username>@<ssh_host>

(Useful for php debugging extension like xdebug, etc)

Start a tunnel from remote machine’s port 80 to your local port 2001
ssh -N -L 2001:localhost:80 <username>@<ssh_host>

Access site at http://localhost:2001 . Also useful to connect phpmyadmin, postgres, mongo, private site etc of remote machine. Change port accordinly.

Compare a remote file with local file
ssh <username>@<ssh_host> "cat /path/to/remotefile" | diff /path/to/localfile -
Mount remote server folder/filesystem to local through SSH
sshfs <username>@<ssh_host>:/path/to/folder /path/to/mount/point

Requires to install SSHFS.

SSH connection through host in the middle
ssh -t <username>@reachable_host ssh <username>@unreachable_host
Copy from host1 to host2, through your host (when host1 and host2 cannot connect directly with each other)
ssh <username>@host1 "cd /somedir/tocopy/ && tar -cf – ." | ssh <username>@host2 "cd /samedir/tocopyto/ && tar -xf -"
Run any GUI program remotely
ssh -fX <username>@<ssh_host> <program>

(SSH Host Remote server requires to have GUI packages like xinit, fluxbox, xvfb etc)

Requires to : (X11Forwarding yes) in /etc/ssh/sshd_config file

Setup a persistent connection to a remote machine and run in background.
ssh -MNf <username>@<ssh_host>

All the SSH connections to the machine will then go through the persistent SSH socket. This is very useful if you are using SSH to synchronize files using (rsync/sftp/cvs/svn) on a regular basis because it won’t create a new socket each time to open an ssh connection.

Attach screen over ssh
ssh -t <username>@<ssh_host> "screen -r"

Directly attach a remote screen session (saves a useless parent bash process)

Screen, a terminal multiplexor, allows to run multiple terminal sessions within a single ssh session, detaching from them and reattaching them as needed. You can avoid the problem to restart a time-consuming process if your SSH session was disconnected.

Remove a line in a text file. Useful to fix and remove bad host
ssh-keygen -R <the_offending_host>

(or use VI/Nano Editor to remove the host)

Remove a line in a text file. Useful to fix “ssh host key change” warnings
sed -i 8d ~/.ssh/known_hosts
Execute complex remote shell commands  from file over ssh, without escaping quotes
ssh host -l user $(<cmd.txt)
ssh host -l user “`cat cmd.txt`”
Pipe mysql db dump from local to remote server
mysqldump –add-drop-table –extended-insert –force –log-error=error.log -uUSER -pPASS OLD_DB_NAME | ssh -C user@newhost "mysql -uUSER -pPASS NEW_DB_NAME"
What to know how fast your ssh connection is? Live ssh network throughput test. Connects to host via ssh and displays the live transfer speed, directing all transferred data to /dev/null
yes | pv | ssh $host "cat > /dev/null"

(http://www.ivarch.com/programs/pv.shtml)

 

Establish a remote Gnu screen session that you can re-connect. Lets to open many open shells with a single remote connection.
ssh -t <username>@<ssh_host> /usr/bin/screen -xRR

If you detach with “Ctrl-a d” or if the ssh session is accidentally terminated, all processes running in your remote shells remain undisturbed, ready for you to reconnect. Other useful screen commands are “Ctrl-a c” (open new shell) and “Ctrl-a a” (alternate between shells). Reference at: http://aperiodic.net/screen/quick_reference

Resume scp of a big file in case transfer fails in between. (Local to Remote)
rsync –partial –progress –rsh=ssh <source_file_path> <username>@<ssh_host>:<target_file_pathdirectory>
Resume scp of a big file in case transfer fails in between. (Local to Remote)
rsync –partial –progress –rsh=ssh  <username>@<ssh_host>:<remote_file_path> <local_file_path>
Analyze traffic remotely over ssh w/ wireshark by piping remote output to local.
ssh <username>@<ssh_host> 'tshark -f "port !22" -w -' | wireshark -k -i –
Capture traffic on a remote machine with tshark, sends the raw pcap data over the ssh link, and displays it in wireshark.
ssh <username>@<ssh_host> tcpdump -w – 'port !22' | wireshark -k -i –
Have an ssh session open forever. Autossh is a tool to monitor and restart SSH connections if and when they drop
autossh -M50000 -t <username>@<ssh_host> 'screen -raAd mysession'
Throttle bandwidth using cstream.

bzip a folder and transfers it over the network to “host” at 777k bit/s.

 

tar -cj /backup | cstream -t 777k | ssh host ‘tar -xj -C /backup’

Reference: http://www.cons.org/cracauer/cstream.html#usage

Copy stdin to your X11 buffer
ssh user@host cat /path/to/some/file | xclip

xclip is a tool to copy the contents of a file directly to the clipboard.

For more options related to SSH command, Refer official MAN Page Documentation : https://man7.org/linux/man-pages/man5/ssh_config.5.html and you can also refer https://explainshell.com/explain to get detailed usage idea of the command.

I hope above list would be helpful to you. I will try to keep the above list updated. Thanks for reading and share if you liked this post.

Akhilesh Yadav Being a Software Engineer, I love documenting my journey and share my learnings with other developers. I have passion for exploring Javascript, AWS Cloud and lot many things.

Leave a Reply

Your email address will not be published. Required fields are marked *