Skip to content

Instantly share code, notes, and snippets.

@jbarotin
Created February 4, 2019 08:44
Show Gist options
  • Save jbarotin/d6e903e53eaec8368034d33ad6e0e577 to your computer and use it in GitHub Desktop.
Save jbarotin/d6e903e53eaec8368034d33ad6e0e577 to your computer and use it in GitHub Desktop.
Scrtipt that aim to reboot a Scaleway bare metal instance
# -*- encoding: utf-8 -*-
#
# This script aim to reboot list of scaleway baremetal instance
#
# prerequisite are the following :
# - scw cli installed and can be found in PATH
# - root ssh key access without password
# - vm os is debian based
# - python 3.6 minimum
#
# use it like this :
# python reboot_scaleway_baremetal.py host_name1 [host_name2] [host_name3]
import subprocess
import sys
import socket
import time
def run(cmd, ignore_errors=False):
print(cmd)
p = subprocess.run(cmd, shell=True)
if not ignore_errors:
if p.returncode != 0:
raise Exception("Something wrong append")
def main(host):
print(f"Handle reboot {host}")
if port_open(host):
print("host is up shutdown it properly")
run(f"ssh root@{host} shutdown -r +1", ignore_errors=True)
print("wait 2 minutes while node shutdown properly")
time.sleep(120)
else:
print(f"{host} is already down")
print(f"reboot {host} though api")
nb_try = 0
time_slice = 300
while not port_open(host) and nb_try < 3:
print(f"try #{nb_try}")
run(f"scw restart {host}", ignore_errors=True)
wait_time = (nb_try+1)*time_slice
print("wait {} minutes for reboot".format(wait_time/60))
time.sleep(wait_time)
nb_try += 1
if port_open(host):
print("Restart OK")
else:
print("KO")
def port_open(host, port=22):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
result = s.connect_ex((host, port))
return result == 0
if __name__ == "__main__":
for i in range(1, len(sys.argv)):
main(sys.argv[i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment