Shell Script to reboot multiple servers.

Writing a shell script to reboot multiple servers, seems to bit overkill, why not just login into server and fire init 6? It’s not feasible when you have 100’s of server and when you want to reboot all of them or combination of few.

Shell Script to reboot multiple servers

There are multiple ways to write a script, one of the best way is to use ansible. However, in some environment it’s not just possible to use ansible due to many reasons. However, If your environment has problems running ansible and you want a quick solution then use shell script. This will make your life easy 🙂

Here is simple shell script to reboot multiple servers, you can add the server names in the command line and then it will go on rebooting every server which you have listed.

Script Usage:-

[[email protected] /]# ./server-reboot.sh appserver1 sqlserver1 dataserver1

Above command will reboot appserver1, sqlserver1 and dataserver1, if you have not setup SSH keys then it will ask for password.

1. Create a file called server-reboot.sh and add the following contents.

#!/bin/bash
for server in "${@}"
do
{
scriptName=$0
scriptPath=$(dirname $0)
script=$scriptPath/boot.txt
command=`base64 -w0 $script`
ssh -t $server "echo $command | base64 -d | sudo bash"
}
done

2. Create a another file named boot.txt in the same location where you have created server-reboot.sh and add the below contents.

for ((i=03; i>0; i--)); do sleep 1 ; printf "\rREBOOTING SERVER in $i Second. PRESS CTRL + C to cancel " ; done
shutdown -rf now

Make sure to give execute permissions to server-reboot.sh

[[email protected]/]# chmod +x server-reboot.sh

It’s just not reboot command but you can add any commands which you want to run on multiple Linux servers in the file boot.txt

As I said earlier, there are many other ways to do the same task. But this is just a simple one.

If your servers are physical then you should always make sure that you have access to remote controller for example Dell DRAC, in case your server doesn’t comes online you will have to check using that.

To add to the above point, in some cases. You might also want to run FSCK. So you will need to evaluate all the things before rebooting the servers.

Spread the love

Leave a Comment