Run a Local Shell Script Remotely Via SSH

At work, I needed to create a script that did several checks such as verifying disk space and CPU utilization; this script is to be run on a number of servers. We wanted to keep a daily record for historical and trending purposes. So, I created a script that performed the necessary steps of outputting the relevant data (using grep) and tested it out on the development machine. When it came time to try it out on more than one machine, I ran into the problem of having to install this same script on every single machine I wanted to gather data from. Certainly not convenient! So, I had to figure out a way to have just one script and run that script on all the target servers.

After some research, I found a method of running a shell script that’s stored locally on a remote host via SSH, assuming bash is installed on the remote host:

ssh [user]@[host] -p [port] 'bash -s' < [script.sh] [script options]

As a test, you can have a simple text file that contains:

ls -la