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 [email protected] "uptime"
If you would like to run more than one command then you can also do this by using a semicolon between commands.
ssh [email protected] "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 [email protected]$a "hostname; commands"; done;
for a in '[email protected]' '[email protected]' '[email protected]'; do ssh $a "hostname; commands"; done;