From 21b25f1cb229e2058610e361627b5d278857497a Mon Sep 17 00:00:00 2001 From: chirac Date: Wed, 11 Jul 2018 02:35:13 +0200 Subject: [PATCH] Generation et application automatique de la conf sur les switchs cibles via rest --- main.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index e66d155..df88191 100755 --- a/main.py +++ b/main.py @@ -6,6 +6,10 @@ from re2oapi import Re2oAPIClient from jinja2 import Environment, FileSystemLoader +import requests +import base64 +import json + config = ConfigParser() config.read('config.ini') @@ -37,6 +41,8 @@ class Switch: self.conf = None self.name = None self.switch = None + self.headers = None + self.creds_dict = None def get_conf_file_name(self): return self.switch["short_name"] + ".conf" @@ -85,6 +91,39 @@ class Switch: self.preprocess_hp() self.conf = self.hp_tpl.render(switch=self.switch, additionals=self.additionals) + def check_and_get_login(self): + """Récupère les login/mdp du switch, renvoie false si ils sont indisponibles""" + self.creds_dict = self.switch["get_management_cred_value"] + if self.creds_dict: + return True + else: + return False + + def login_hp(self): + """Login into rest interface of this switch""" + url_login = "http://" + self.switch["ipv4"] + "/rest/v3/login-sessions" + + payload_login = { + "userName" : self.creds_dict["id"], + "password" : self.creds_dict["pass"] + } + get_cookie = requests.post(url_login, data=json.dumps(payload_login)) + cookie = get_cookie.json()['cookie'] + self.headers = {"Cookie" : cookie} + + def apply_conf_hp(self): + """Apply config restore via rest""" + url_restore = "http://" + self.switch["ipv4"] + "/rest/v4/system/config/cfg_restore" + data = { + "server_type": "ST_TFTP", + "file_name": self.get_conf_file_name(), + "tftp_server_address": {"server_address": + {"ip_address": + {"version":"IAV_IP_V4", + "octets":"10.231.100.249"}}}, + } + # Nous lançons la requête de type POST. + post_restore = requests.post(url_restore, data=json.dumps(data), headers=self.headers) def gen_conf_and_write(self): """Génère la conf suivant le bon constructeur et l'écrit""" @@ -94,6 +133,14 @@ class Switch: self.gen_conf_hp() self.write_conf() + def apply_conf(self): + if self.check_and_get_login(): + if self.switch["model"] and self.switch["automatic_provision"] == True: + constructor = self.switch["model"]["constructor"].lower() + if "hp" in constructor or "aruba" in constructor: + self.login_hp() + self.apply_conf_hp() + def write_conf(self): """Ecriture de la conf du switch dans le fichier qui va bien""" with open("generated/" + self.get_conf_file_name(), 'w+') as f: @@ -105,7 +152,8 @@ print("gen tpl") sw = Switch() for switch in all_switchs: sw.switch = switch -# sw.gen_conf_and_write() - sw.gen_conf_hp() - sw.write_conf() + sw.gen_conf_and_write() + sw.apply_conf() +# sw.gen_conf_hp() +# sw.write_conf()