Linux for Network Engineers: How to Execute Commands Remotely with SSH

Secure Shell (ssh) is the standard way to connect to a remote machine’s shell. We routinely log in and use ssh to establish an interactive session and stay logged in as long as necessary. 

I often need to execute a single non-interactive command on a remote host such as to check a log file or a machine’s free disk space. Obviously, that can be accomplished by establishing an interactive session, run the command, and exit as follows:

Here is the step-by-step process:

  1. Logged into the remote machine
  2. Executed the command
  3. Logged out of the remote machine

Note that I had set up passwordless ssh beforehand to avoid typing in my password every single time.

This is not too bad, but when there is a better option why not use it?

The alternative is execute the command via ssh on the remote host as follows:

As you can see I added the command df -h after the ssh login information, the command executed on the remote machine, and the output was printed on my local shell. This may not seem like a big deal, but I personally use it very often to get the IP address assigned by my DHCP server to a machine that just connected to the network as follows:

In this case, I know that the DHCP server logs in /var/log/syslog all IP assignments. With the remote execution of the tail /var/log/syslog command on the DHCP server at I see that the last assigned IP was I can also see the MAC address of the machine that this IP was assigned to was b8:27:eb:90:64:9b and from there I can identify the machine that got that IP.

The other benefit of remote execution of non-interactive commands with ssh is that you can include them in scripts since the output can be parsed like any other command output. For example, here is a script that checks if the root partition of a remote host is 90% full, and if it is it prompts to delete the 10 largest files in the /var/log/ directory:

This is just a pointer to the remote command execution with ssh and just a few examples of how I use this as part of my daily Linux administration tasks. Drop me a line in the comments if you find any good use cases of this as well.