Running Commands Automatically Over SSH

In this quick and simple post I will be showing you an easy way to automatically run commands over SSH. This method works great with bash loops if you need to run the same commands over multiple servers. Using this method automatically disconnects once the command or commands are finished executing, you will receive the full output however.

Automatically Run Commands Once Connected

To accomplish this you simply enter the commands after the domain or IP you intend to ssh to. Here is an example of running the uptime command below:

ssh "uptime"

If you would like to run more than one command then you can also do this by using a semicolon between commands.

ssh "hostname; uptime; uname -r"

Automatically Run Commands On Multiple Servers

You can accomplish this by either using parellels (will write a post on this at a later date) or by using a for loop. You do not need to save this as a script if you are using bash, simply run the loop directly in your terminal. You can switch to bash if you are using another shell by running /bin/bash.

If you are doing this on multiple servers I recommend running the hostname command first as it makes it easier to see which server gave which response. Here are two examples of using a for loop to accomplish this.

for a in 'server1' 'server2' 'server3'; do
ssh username@$a "hostname; commands";
for a in 'username@server1' 'username@server2' 'username@server3'; do
ssh $a "hostname; commands";

I hope you enjoyed this quick and simple post, please don’t forget to like, comment, or share to support this blog. Thank you!

Leave a Reply

Protected with IP Blacklist CloudIP Blacklist Cloud