JustGeek.dev Tech, simplified.

Shell Script to Reboot Multiple Servers

Rebooting multiple servers manually can be a tedious task, especially when dealing with hundreds of servers. While you could log in to each server and run init 6, this approach becomes impractical at scale. Automating the process with a shell script can save significant time and effort.

Although tools like Ansible are ideal for such tasks, there are scenarios where using Ansible might not be feasible. In such cases, a simple shell script can provide an effective solution.

Usage

Here’s how to use the script:

[root@server /]# ./server-reboot.sh appserver1 sqlserver1 dataserver1

This command will reboot appserver1, sqlserver1, and dataserver1. If SSH keys are not set up, you will be prompted to enter a password.


Steps to Create the Script

1. Create the server-reboot.sh Script

Create a file named server-reboot.sh and add the following code:

#!/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 the boot.txt File

In the same directory as server-reboot.sh, create another file named boot.txt with the following content:

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

3. Grant Execute Permissions

Make the script executable by running:

[root@justgeek/]# chmod +x server-reboot.sh

Customizing the Script

You can customize the boot.txt file to include any commands you want to execute on multiple Linux servers. For instance, you might want to include pre-reboot checks or notifications.


Important Considerations

  • Physical Servers: Ensure you have access to remote management tools like Dell DRAC in case a server fails to come back online after a reboot.
  • FSCK Requirements: If your servers need a file system check (FSCK), plan accordingly before rebooting.
  • Testing: Test the script in a controlled environment to avoid unintended disruptions.

By using this script, you can streamline server reboots and manage your infrastructure more efficiently. For more complex tasks or environments, consider integrating tools like Ansible or Puppet.