Python script to reboot server N times

3.3k views Asked by At

I'm trying to stress test several servers that I can ssh into. I'm trying to write a python script that causes a reboot loop for N times. I call

os.system('reboot') 

But, I'm not sure how to have the script continue execution once the server has finished booting to continue execution. The servers do run various distros of Linux. Any help would be great.

2

There are 2 answers

0
AudioBubble On BEST ANSWER

You mentioned that the solution doesn't have to be in Python, so you can just use a Bash script for this (given that you can ping the server):

#!/usr/bin/env bash
COUNTER=$1
SERVER=$2
COMMAND="sudo reboot"
SLEEP_DURATION=60

echo "Working on $SERVER $COUNTER times"

while (( $COUNTER > 0 )); do
    ping -c 1 -t 5 $SERVER;
    _ping_r=$?
    if (( $_ping_r < 1 )); then
        echo "Rebooting $SERVER"
        ssh $SERVER $COMMAND;
        let COUNTER=COUNTER-1
    else
        echo "Couldn't ping $SERVER.  Taking a quick nap and trying again."
        sleep 5
    fi
    sleep $SLEEP_DURATION;
done

echo "Done working on $SERVER"

Save it in something like command_runner.sh and simply call it via ./command_runner.sh 2 server.example.org on a workstation that can SSH and run reboot on the server.

0
jfs On

You could use Fabric to ssh into several servers in parallel and to execute various commands there (even those commands that require reboot -- you might need to disconnect all servers explicitly in your fabfile.py after such commands).