From d1b4f569134bb070d54a7193d7a6f8d2eda1c575 Mon Sep 17 00:00:00 2001 From: chirac Date: Sun, 8 Jul 2018 19:13:58 +0200 Subject: [PATCH 01/34] Generateur de confi de switch HP --- .gitignore | 1 + generated/__init__.py | 0 main.py | 53 ++++++++++++++++++++-- templates/{hp_test.tpl => hp.tpl} | 74 +++++++++++++++++++++++++++++-- 4 files changed, 121 insertions(+), 7 deletions(-) create mode 100644 generated/__init__.py rename templates/{hp_test.tpl => hp.tpl} (52%) diff --git a/.gitignore b/.gitignore index 641c4cc..9e2266d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ config.ini **/__pycache__/** **.list +generated/* diff --git a/generated/__init__.py b/generated/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main.py b/main.py index 46e6de9..697aaf3 100755 --- a/main.py +++ b/main.py @@ -19,17 +19,62 @@ api_client = Re2oAPIClient(api_hostname, api_username, api_password) client_hostname = socket.gethostname().split('.', 1)[0] +print("get switchs conf") all_switchs = api_client.list("switchs/ports-config/") - +all_vlans = api_client.list("machines/vlan/") +all_roles = api_client.list("machines/role/") # Création de l'environnement Jinja ENV = Environment(loader=FileSystemLoader('.')) # Import du fichier template dans une variable "template" -template = ENV.get_template("templates/hp_test.tpl") +template = ENV.get_template("templates/hp.tpl") # Création du template final avec les valeurs contenues dans le dictionnaire "valeurs" - Ces valeurs sont positionnées dans un objet "temp", qui sera utilisé par le moteur, et que l'on retrouve dans le template. -conf = template.render(switch=all_switchs[2]) -print(all_switchs[2]) +def preprocess(switch): + def add_to_vlans(vlans, vlan, port, tagged=True): + if not vlan['vlan_id'] in vlans: + if not tagged: + vlans[vlan['vlan_id']] = {'ports_untagged' : [str(port['port'])], 'ports_tagged' : [], 'name' : vlan['name']} + else: + vlans[vlan['vlan_id']] = {'ports_tagged' : [str(port['port'])], 'ports_untagged' : [], 'name' : vlan['name']} + else: + if not tagged: + vlans[vlan['vlan_id']]['ports_untagged'].append(str(port['port'])) + else: + vlans[vlan['vlan_id']]['ports_tagged'].append(str(port['port'])) + + ra_guarded = [] + loop_protected = [] + vlans = dict() + + for port in switch['ports']: + if port['get_port_profil']['loop_protect']: + loop_protected.append(str(port['port'])) + if port['get_port_profil']['ra_guard']: + ra_guarded.append(str(port['port'])) + + if port['get_port_profil']['vlan_untagged']: + add_to_vlans(vlans, port['get_port_profil']['vlan_untagged'], port, tagged=False) + if port['get_port_profil']['vlan_tagged']: + for vlan in port['get_port_profil']['vlan_tagged']: + add_to_vlans(vlans, vlan, port) + + arp_protect_vlans = [vlan["vlan_id"] for vlan in all_vlans if vlan["arp_protect"]] + dhcp_snooping_vlans = [vlan["vlan_id"] for vlan in all_vlans if vlan["dhcp_snooping"]] + dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in all_vlans if vlan["dhcpv6_snooping"]] + ntp_servers = [server["servers"] for server in all_roles if server["role_type"] == "ntp-server"][0] + log_servers = [server["servers"] for server in all_roles if server["role_type"] == "log-server"][0] + + return {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers} + +print("gen tpl") +conf = template.render(switch=all_switchs[2], additionals=preprocess(all_switchs[2])) + +for switch in all_switchs: + with open("generated/" + switch["short_name"] + ".conf", 'w+') as f: + f.write(template.render(switch=switch, additionals=preprocess(switch))) + + print(conf) diff --git a/templates/hp_test.tpl b/templates/hp.tpl similarity index 52% rename from templates/hp_test.tpl rename to templates/hp.tpl index 1ef99a8..90c9f20 100644 --- a/templates/hp_test.tpl +++ b/templates/hp.tpl @@ -12,12 +12,58 @@ snmpv3 restricted-access snmpv3 user "crans" snmpv3 group ManagerPriv user "crans" sec-model ver3 snmp-server community "public" Operator +;--- Heure/date +time timezone 60 +time daylight-time-rule Western-Europe +{%- for server in additionals.ntp_servers %} +{%- for interface in server.interface %} +{%- if switch.subnet.0.vlan_id == interface.vlan_id %} +sntp server priority {{ loop.index }} {{ interface.ipv4 }} 4 +{%- if interface.ipv6 %} +sntp server priority {{ loop.index + 1 }} {{ interface.ipv6.0.ipv6 }} 4 +{%- endif %} +{%- endif %} +{%- endfor %} +{%- endfor %} timesync sntp sntp unicast ;--- Misc --- console inactivity-timer 30 +;--- Logs --- +{%- for server in additionals.log_servers %} +{%- for interface in server.interface %} +{%- if switch.subnet.0.vlan_id == interface.vlan_id %} +logging {{ interface.ipv4 }} +{%- if interface.ipv6 %} +logging {{ interface.ipv6.0.ipv6 }} +{%- endif %} +{%- endif %} +{%- endfor %} +{%- endfor %} ;--- IP du switch --- no ip default-gateway +max-vlans 256 +{%- for id, vlan in additionals.vlans.items() %} +vlan {{ id }} + name "{{ vlan["name"]|capitalize }}" + {%- if vlan["ports_tagged"] %} + tagged {{ vlan["ports_tagged"]|join(' ') }} + {%- endif %} + {%- if vlan["ports_untagged"] %} + untagged {{ vlan["ports_untagged"]|join(' ') }} + {%- endif %} + {%- if switch.subnet.0.vlan_id == id %} + ip address {{ switch.ipv4 }} {{ switch.subnet.0.netmask }} + {%- else %} + no ip address + {%- endif %} + {%- if switch.subnet.0.vlan_id == id %} + ipv6 address {{ switch.ipv6 }} {{ switch.subnet6.netmask }} + {%- else %} + no ipv6 enable + {%- endif %} +exit +{%- endfor %} ;--- Accès d'administration --- no telnet-server no web-management @@ -25,19 +71,41 @@ aaa authentication ssh login public-key none aaa authentication ssh enable public-key none ip ssh ip ssh filetransfer -ip authorized-managers {{ switch.subnet.0.network }} {{switch.subnet.0.netmask }} access manager +ip authorized-managers {{ switch.subnet.0.network }} {{ switch.subnet.0.netmask }} access manager {%- if switch.subnet6 %} -ipv6 authorized-managers {{ switch.subnet6.network }} {{switch.subnet6.netmask }} access manager +ipv6 authorized-managers {{ switch.subnet6.network }} {{ switch.subnet6.netmask }} access manager {%- endif %} +{%- if additionals.loop_protected %} ;--- Protection contre les boucles --- loop-protect disable-timer 30 loop-protect transmit-interval 3 +loop-protect {{ additionals.loop_protected|join(' ') }} +{%- endif %} radius-server dyn-autz-port 3799 ;--- Filtrage mac --- aaa port-access mac-based addr-format multi-colon ;--- Bricoles --- no cdp run +{%- if additionals.dhcp_snooping_vlans %} +;--- DHCP Snooping --- +dhcp-snooping vlan {{ additionals.dhcp_snooping_vlans|join(' ') }} dhcp-snooping +{%- endif %} +{%- if additionals.arp_protect_vlans %} +;--- ARP Protect --- +arp-protect +arp-protect vlan {{ additionals.arp_protect_vlans|join(' ') }} +arp-protect validate src-mac dest-mac +{%- endif %} +{%- if additionals.dhcpv6_snooping_vlans %} +;--- DHCPv6 Snooping --- +dhcpv6-snooping vlan {{ additionals.dhcpv6_snooping_vlans|join(' ') }} +dhcpv6-snooping +{%- endif %} +{%- if additionals.ra_guarded %} +;--- RA guards --- +ipv6 ra-guard ports {{ additionals.ra_guarded|join(' ')}} +{%- endif %} ;--- Config des prises --- {%- for port in switch.ports %} {%- if port.get_port_profil.radius_type == "802.1X" %} @@ -61,7 +129,7 @@ interface {{ port.port }} {%- else %} disable {%- endif %} - name "{{ port.port }}" + name "{{ port.pretty_name }}" {%- if port.get_port_profil.flow_control %} flow control {%- endif %} From adf81b8b3a5ac5f2cab4d7381265f01dba2c4968 Mon Sep 17 00:00:00 2001 From: chirac Date: Sun, 8 Jul 2018 19:26:06 +0200 Subject: [PATCH 02/34] =?UTF-8?q?Authorisation=20des=20ip=20des=20dhcp=20l?= =?UTF-8?q?=C3=A9gitimes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 3 ++- templates/hp.tpl | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index 697aaf3..03bcb72 100755 --- a/main.py +++ b/main.py @@ -66,8 +66,9 @@ def preprocess(switch): dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in all_vlans if vlan["dhcpv6_snooping"]] ntp_servers = [server["servers"] for server in all_roles if server["role_type"] == "ntp-server"][0] log_servers = [server["servers"] for server in all_roles if server["role_type"] == "log-server"][0] + dhcp_servers = [server["servers"] for server in all_roles if server["role_type"] == "dhcp"][0] - return {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers} + return {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers, 'dhcp_servers' : dhcp_servers} print("gen tpl") conf = template.render(switch=all_switchs[2], additionals=preprocess(all_switchs[2])) diff --git a/templates/hp.tpl b/templates/hp.tpl index 90c9f20..fc825b9 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -88,6 +88,11 @@ aaa port-access mac-based addr-format multi-colon no cdp run {%- if additionals.dhcp_snooping_vlans %} ;--- DHCP Snooping --- +{%- for server in additionals.dhcp_servers %} +{%- for interface in server.interface %} +dhcp-snooping authorized-server {{ interface.ipv4 }} +{%- endfor %} +{%- endfor %} dhcp-snooping vlan {{ additionals.dhcp_snooping_vlans|join(' ') }} dhcp-snooping {%- endif %} From 610a43c919192e79bc62124763cefe8a7446be13 Mon Sep 17 00:00:00 2001 From: chirac Date: Sun, 8 Jul 2018 19:59:13 +0200 Subject: [PATCH 03/34] =?UTF-8?q?Remaniement,=20syst=C3=A8me=20de=20class?= =?UTF-8?q?=20pour=20g=C3=A9rer=20les=20constructeurs=20differents?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 100 ++++++++++++++++++++++++++++++++------------------------ 1 file changed, 58 insertions(+), 42 deletions(-) diff --git a/main.py b/main.py index 03bcb72..b9f9d5a 100755 --- a/main.py +++ b/main.py @@ -13,69 +13,85 @@ api_hostname = config.get('Re2o', 'hostname') api_password = config.get('Re2o', 'password') api_username = config.get('Re2o', 'username') - - api_client = Re2oAPIClient(api_hostname, api_username, api_password) client_hostname = socket.gethostname().split('.', 1)[0] print("get switchs conf") all_switchs = api_client.list("switchs/ports-config/") -all_vlans = api_client.list("machines/vlan/") -all_roles = api_client.list("machines/role/") # Création de l'environnement Jinja ENV = Environment(loader=FileSystemLoader('.')) -# Import du fichier template dans une variable "template" -template = ENV.get_template("templates/hp.tpl") # Création du template final avec les valeurs contenues dans le dictionnaire "valeurs" - Ces valeurs sont positionnées dans un objet "temp", qui sera utilisé par le moteur, et que l'on retrouve dans le template. -def preprocess(switch): - def add_to_vlans(vlans, vlan, port, tagged=True): - if not vlan['vlan_id'] in vlans: - if not tagged: - vlans[vlan['vlan_id']] = {'ports_untagged' : [str(port['port'])], 'ports_tagged' : [], 'name' : vlan['name']} + +class Switch: + def __init__(self): + self.additionnal = None + self.all_vlans = api_client.list("machines/vlan/") + self.all_roles = api_client.list("machines/role/") + # Import du fichier template dans une variable "template" + self.hp_tpl = ENV.get_template("templates/hp.tpl") + self.conf = None + self.name = None + self.switch = None + + def get_conf_file_name(self): + return self.switch["short_name"] + ".conf" + + def preprocess_hp(self): + """Prérempli certains valeurs renvoyées directement à jinja, pour plus de simplicité""" + + def add_to_vlans(vlans, vlan, port, tagged=True): + if not vlan['vlan_id'] in vlans: + if not tagged: + vlans[vlan['vlan_id']] = {'ports_untagged' : [str(port['port'])], 'ports_tagged' : [], 'name' : vlan['name']} + else: + vlans[vlan['vlan_id']] = {'ports_tagged' : [str(port['port'])], 'ports_untagged' : [], 'name' : vlan['name']} else: - vlans[vlan['vlan_id']] = {'ports_tagged' : [str(port['port'])], 'ports_untagged' : [], 'name' : vlan['name']} - else: - if not tagged: - vlans[vlan['vlan_id']]['ports_untagged'].append(str(port['port'])) - else: - vlans[vlan['vlan_id']]['ports_tagged'].append(str(port['port'])) + if not tagged: + vlans[vlan['vlan_id']]['ports_untagged'].append(str(port['port'])) + else: + vlans[vlan['vlan_id']]['ports_tagged'].append(str(port['port'])) - ra_guarded = [] - loop_protected = [] - vlans = dict() + vlans = dict() - for port in switch['ports']: - if port['get_port_profil']['loop_protect']: - loop_protected.append(str(port['port'])) - if port['get_port_profil']['ra_guard']: - ra_guarded.append(str(port['port'])) + for port in self.switch['ports']: + if port['get_port_profil']['vlan_untagged']: + add_to_vlans(vlans, port['get_port_profil']['vlan_untagged'], port, tagged=False) + if port['get_port_profil']['vlan_tagged']: + for vlan in port['get_port_profil']['vlan_tagged']: + add_to_vlans(vlans, vlan, port) - if port['get_port_profil']['vlan_untagged']: - add_to_vlans(vlans, port['get_port_profil']['vlan_untagged'], port, tagged=False) - if port['get_port_profil']['vlan_tagged']: - for vlan in port['get_port_profil']['vlan_tagged']: - add_to_vlans(vlans, vlan, port) + arp_protect_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["arp_protect"]] + dhcp_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcp_snooping"]] + dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcpv6_snooping"]] + ntp_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "ntp-server"][0] + log_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "log-server"][0] + dhcp_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "dhcp"][0] + ra_guarded = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['ra_guard']] + loop_protected = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['loop_protect']] - arp_protect_vlans = [vlan["vlan_id"] for vlan in all_vlans if vlan["arp_protect"]] - dhcp_snooping_vlans = [vlan["vlan_id"] for vlan in all_vlans if vlan["dhcp_snooping"]] - dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in all_vlans if vlan["dhcpv6_snooping"]] - ntp_servers = [server["servers"] for server in all_roles if server["role_type"] == "ntp-server"][0] - log_servers = [server["servers"] for server in all_roles if server["role_type"] == "log-server"][0] - dhcp_servers = [server["servers"] for server in all_roles if server["role_type"] == "dhcp"][0] + self.additionals = {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers, 'dhcp_servers' : dhcp_servers} - return {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers, 'dhcp_servers' : dhcp_servers} + + def gen_conf_hp(self): + """Génère la config pour ce switch hp""" + self.preprocess_hp() + self.conf = self.hp_tpl.render(switch=self.switch, additionals=self.additionals) + + def write_conf(self): + with open("generated/" + self.get_conf_file_name(), 'w+') as f: + f.write(self.conf) print("gen tpl") -conf = template.render(switch=all_switchs[2], additionals=preprocess(all_switchs[2])) + +sw = Switch() for switch in all_switchs: - with open("generated/" + switch["short_name"] + ".conf", 'w+') as f: - f.write(template.render(switch=switch, additionals=preprocess(switch))) + sw.switch = switch + sw.gen_conf_hp() + sw.write_conf() - -print(conf) From a477b2a889ecf730c8a93c7f4663fd70c40c1d9f Mon Sep 17 00:00:00 2001 From: chirac Date: Sun, 8 Jul 2018 20:31:04 +0200 Subject: [PATCH 04/34] Gestion igmp et mld par vlans --- main.py | 5 ++++- templates/hp.tpl | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index b9f9d5a..1d34073 100755 --- a/main.py +++ b/main.py @@ -68,13 +68,16 @@ class Switch: arp_protect_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["arp_protect"]] dhcp_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcp_snooping"]] dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcpv6_snooping"]] + igmp_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["igmp"]] + mld_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["mld"]] ntp_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "ntp-server"][0] log_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "log-server"][0] dhcp_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "dhcp"][0] + radius_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "radius-server"][0] ra_guarded = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['ra_guard']] loop_protected = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['loop_protect']] - self.additionals = {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers, 'dhcp_servers' : dhcp_servers} + self.additionals = {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers, 'dhcp_servers' : dhcp_servers, 'radius_servers' : radius_servers, 'igmp_vlans' : igmp_vlans, 'mld_vlans': mld_vlans} def gen_conf_hp(self): diff --git a/templates/hp.tpl b/templates/hp.tpl index fc825b9..9e35d54 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -62,6 +62,15 @@ vlan {{ id }} {%- else %} no ipv6 enable {%- endif %} + {%- if id in additionals.igmp_vlans %} + ip igmp + no ip igmp querier + {%- endif %} + {%- if id in additionals.mld_vlans %} + no ipv6 mld querier + ipv6 mld version 1 + ipv6 mld enable + {%- endif %} exit {%- endfor %} ;--- Accès d'administration --- @@ -81,6 +90,16 @@ loop-protect disable-timer 30 loop-protect transmit-interval 3 loop-protect {{ additionals.loop_protected|join(' ') }} {%- endif %} +;--- Serveurs Radius +radius-server dead-time 2 +{%- for server in additionals.radius_servers %} +{%- for interface in server.interface %} +{%- if switch.subnet.0.vlan_id == interface.vlan_id %} +radius-server host {{ interface.ipv4 }} key "plop" +radius-server host {{ interface.ipv4 }} dyn-authorization +{%- endif %} +{%- endfor %} +{%- endfor %} radius-server dyn-autz-port 3799 ;--- Filtrage mac --- aaa port-access mac-based addr-format multi-colon From 465c96492e0f8630e0e046582a751616c0f3d174 Mon Sep 17 00:00:00 2001 From: chirac Date: Sun, 8 Jul 2018 22:47:03 +0200 Subject: [PATCH 05/34] Affichage de la version de la conf du switch --- templates/hp.tpl | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index 9e35d54..091afda 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -1,16 +1,14 @@ -; {{ switch.model.reference }}A Configuration Editor; Created on release #{{ firmware }} +; {{ switch.model.reference }}A Configuration Editor; Created on release #{{ switch.model.firmware }} hostname "{{ switch.short_name }}" ; Generated on {{ date_gen }} by re2o ;--- Snmp --- -snmp-server contact "root@crans.org" snmp-server location "{{ switch.switchbay.name }}" ;A faire à la main snmpv3 enable snmpv3 restricted-access -;snmpv3 user "initial" -snmpv3 user "crans" -snmpv3 group ManagerPriv user "crans" sec-model ver3 +snmpv3 user "re2o" +snmpv3 group ManagerPriv user "re2o" sec-model ver3 snmp-server community "public" Operator ;--- Heure/date time timezone 60 From 9566a0d6705fb0550ad47588c56d6e794d643a0b Mon Sep 17 00:00:00 2001 From: chirac Date: Mon, 9 Jul 2018 00:12:38 +0200 Subject: [PATCH 06/34] Formatage de certains options non correct --- templates/hp.tpl | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index 091afda..bfc72b7 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -3,7 +3,9 @@ hostname "{{ switch.short_name }}" ; Generated on {{ date_gen }} by re2o ;--- Snmp --- +{%- if switch.switchbay.name %} snmp-server location "{{ switch.switchbay.name }}" +{%- endif %} ;A faire à la main snmpv3 enable snmpv3 restricted-access @@ -45,10 +47,10 @@ max-vlans 256 vlan {{ id }} name "{{ vlan["name"]|capitalize }}" {%- if vlan["ports_tagged"] %} - tagged {{ vlan["ports_tagged"]|join(' ') }} + tagged {{ vlan["ports_tagged"]|join(',') }} {%- endif %} {%- if vlan["ports_untagged"] %} - untagged {{ vlan["ports_untagged"]|join(' ') }} + untagged {{ vlan["ports_untagged"]|join(',') }} {%- endif %} {%- if switch.subnet.0.vlan_id == id %} ip address {{ switch.ipv4 }} {{ switch.subnet.0.netmask }} @@ -86,7 +88,7 @@ ipv6 authorized-managers {{ switch.subnet6.network }} {{ switch.subnet6.netmask ;--- Protection contre les boucles --- loop-protect disable-timer 30 loop-protect transmit-interval 3 -loop-protect {{ additionals.loop_protected|join(' ') }} +loop-protect {{ additionals.loop_protected|join(',') }} {%- endif %} ;--- Serveurs Radius radius-server dead-time 2 @@ -126,7 +128,7 @@ dhcpv6-snooping {%- endif %} {%- if additionals.ra_guarded %} ;--- RA guards --- -ipv6 ra-guard ports {{ additionals.ra_guarded|join(' ')}} +ipv6 ra-guard ports {{ additionals.ra_guarded|join(',')}} {%- endif %} ;--- Config des prises --- {%- for port in switch.ports %} @@ -153,7 +155,7 @@ interface {{ port.port }} {%- endif %} name "{{ port.pretty_name }}" {%- if port.get_port_profil.flow_control %} - flow control + flow-control {%- endif %} {%- if not port.get_port_profil.dhcp_snooping %} dhcp-snooping trust From a4922017e8975a3b08348ece5d98ac136128882f Mon Sep 17 00:00:00 2001 From: chirac Date: Mon, 9 Jul 2018 00:36:55 +0200 Subject: [PATCH 07/34] Notation cidr pour les ip des switchs --- templates/hp.tpl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index bfc72b7..87a22e7 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -53,12 +53,12 @@ vlan {{ id }} untagged {{ vlan["ports_untagged"]|join(',') }} {%- endif %} {%- if switch.subnet.0.vlan_id == id %} - ip address {{ switch.ipv4 }} {{ switch.subnet.0.netmask }} + ip address {{ switch.ipv4 }}/{{ switch.subnet.0.netmask_cidr }} {%- else %} no ip address {%- endif %} {%- if switch.subnet.0.vlan_id == id %} - ipv6 address {{ switch.ipv6 }} {{ switch.subnet6.netmask }} + ipv6 address {{ switch.ipv6 }}/{{ switch.subnet6.netmask_cidr }} {%- else %} no ipv6 enable {%- endif %} From b1319bfcc219fe071ad56bfbfa02dc9931456ba2 Mon Sep 17 00:00:00 2001 From: chirac Date: Mon, 9 Jul 2018 00:43:21 +0200 Subject: [PATCH 08/34] Fonction aiguillage suivant constructeur --- main.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/main.py b/main.py index 1d34073..e66d155 100755 --- a/main.py +++ b/main.py @@ -85,7 +85,17 @@ class Switch: self.preprocess_hp() self.conf = self.hp_tpl.render(switch=self.switch, additionals=self.additionals) + + def gen_conf_and_write(self): + """Génère la conf suivant le bon constructeur et l'écrit""" + if self.switch["model"]: + constructor = self.switch["model"]["constructor"].lower() + if "hp" in constructor or "aruba" in constructor: + self.gen_conf_hp() + self.write_conf() + 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: f.write(self.conf) @@ -95,6 +105,7 @@ 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() From 64aa4ad521b6201be8209ff00a8dca70eda99617 Mon Sep 17 00:00:00 2001 From: chirac Date: Mon, 9 Jul 2018 23:42:26 +0200 Subject: [PATCH 09/34] Gestion de l'interface rest dans le template --- templates/hp.tpl | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/templates/hp.tpl b/templates/hp.tpl index 87a22e7..f67b0cf 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -75,7 +75,15 @@ exit {%- endfor %} ;--- Accès d'administration --- no telnet-server +{%- if switch.web_management_enabled %} +web-management ssl +web-management plaintext +{%- else %} no web-management +{%- endif %} +{%- if switch.rest_enabled %} +rest-interface +{%- endif %} aaa authentication ssh login public-key none aaa authentication ssh enable public-key none ip ssh From aca526940556a796977727e54779b62d99c8bb75 Mon Sep 17 00:00:00 2001 From: chirac Date: Tue, 10 Jul 2018 00:04:11 +0200 Subject: [PATCH 10/34] =?UTF-8?q?Web=20management=20ssl=20d=C3=A9sactiv?= =?UTF-8?q?=C3=A9=20par=20defaut=20(putain=20de=20clef=20hp=20)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- templates/hp.tpl | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index f67b0cf..310f8c2 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -76,8 +76,12 @@ exit ;--- Accès d'administration --- no telnet-server {%- if switch.web_management_enabled %} -web-management ssl +{%- if switch.web_management_enabled != "ssl" %} web-management plaintext +{%- endif %} +{%- if switch.web_management_enabled == "ssl" %} +web-management ssl +{%- endif %} {%- else %} no web-management {%- endif %} From 1490d59ebacaa39b27a3f047d46dbdde095f3ecd Mon Sep 17 00:00:00 2001 From: chirac Date: Wed, 11 Jul 2018 01:20:55 +0200 Subject: [PATCH 11/34] Gestion de la clef radius dans la conf des switchs --- templates/hp.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index 310f8c2..72b1463 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -107,7 +107,7 @@ radius-server dead-time 2 {%- for server in additionals.radius_servers %} {%- for interface in server.interface %} {%- if switch.subnet.0.vlan_id == interface.vlan_id %} -radius-server host {{ interface.ipv4 }} key "plop" +radius-server host {{ interface.ipv4 }} key "{{ switch.get_radius_key_value }}" radius-server host {{ interface.ipv4 }} dyn-authorization {%- endif %} {%- endfor %} From 21b25f1cb229e2058610e361627b5d278857497a Mon Sep 17 00:00:00 2001 From: chirac Date: Wed, 11 Jul 2018 02:35:13 +0200 Subject: [PATCH 12/34] 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() From 7d7c7f2f13ba998ce24ebd43c62a54ebc43b1900 Mon Sep 17 00:00:00 2001 From: chirac Date: Wed, 11 Jul 2018 02:49:43 +0200 Subject: [PATCH 13/34] Rattrappage de l'erreur si l'apply conf marche pas --- main.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/main.py b/main.py index df88191..63a5416 100755 --- a/main.py +++ b/main.py @@ -21,7 +21,6 @@ api_client = Re2oAPIClient(api_hostname, api_username, api_password) client_hostname = socket.gethostname().split('.', 1)[0] -print("get switchs conf") all_switchs = api_client.list("switchs/ports-config/") # Création de l'environnement Jinja @@ -146,14 +145,13 @@ class Switch: with open("generated/" + self.get_conf_file_name(), 'w+') as f: f.write(self.conf) -print("gen tpl") sw = Switch() for switch in all_switchs: sw.switch = switch sw.gen_conf_and_write() - sw.apply_conf() -# sw.gen_conf_hp() -# sw.write_conf() - + try: + sw.apply_conf() + except: + print("Erreur dans l'application de la conf pour " + switch["short_name"]) From 3d7c9d98be772fa52e10d867e6817fb67a0857a4 Mon Sep 17 00:00:00 2001 From: chirac Date: Wed, 11 Jul 2018 23:58:16 +0200 Subject: [PATCH 14/34] =?UTF-8?q?Utilise=20les=20r=C3=A9glages=20roles=20e?= =?UTF-8?q?t=20topologie=20option=20pour=20reconfig=20les=20switchs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 12 ++++-------- templates/hp.tpl | 48 ++++++++++++++++++------------------------------ 2 files changed, 22 insertions(+), 38 deletions(-) diff --git a/main.py b/main.py index 63a5416..4d71553 100755 --- a/main.py +++ b/main.py @@ -34,7 +34,7 @@ class Switch: def __init__(self): self.additionnal = None self.all_vlans = api_client.list("machines/vlan/") - self.all_roles = api_client.list("machines/role/") + self.settings = api_client.view("preferences/optionaltopologie/") # Import du fichier template dans une variable "template" self.hp_tpl = ENV.get_template("templates/hp.tpl") self.conf = None @@ -75,20 +75,16 @@ class Switch: dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcpv6_snooping"]] igmp_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["igmp"]] mld_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["mld"]] - ntp_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "ntp-server"][0] - log_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "log-server"][0] - dhcp_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "dhcp"][0] - radius_servers = [server["servers"] for server in self.all_roles if server["role_type"] == "radius-server"][0] ra_guarded = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['ra_guard']] loop_protected = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['loop_protect']] - self.additionals = {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'ntp_servers': ntp_servers, 'log_servers': log_servers, 'dhcp_servers' : dhcp_servers, 'radius_servers' : radius_servers, 'igmp_vlans' : igmp_vlans, 'mld_vlans': mld_vlans} + self.additionals = {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'igmp_vlans' : igmp_vlans, 'mld_vlans': mld_vlans} def gen_conf_hp(self): """Génère la config pour ce switch hp""" self.preprocess_hp() - self.conf = self.hp_tpl.render(switch=self.switch, additionals=self.additionals) + self.conf = self.hp_tpl.render(switch=self.switch, settings=self.settings, additionals=self.additionals) def check_and_get_login(self): """Récupère les login/mdp du switch, renvoie false si ils sont indisponibles""" @@ -119,7 +115,7 @@ class Switch: "tftp_server_address": {"server_address": {"ip_address": {"version":"IAV_IP_V4", - "octets":"10.231.100.249"}}}, + "octets":self.settings["switchs_management_interface_ip"]}}}, } # Nous lançons la requête de type POST. post_restore = requests.post(url_restore, data=json.dumps(data), headers=self.headers) diff --git a/templates/hp.tpl b/templates/hp.tpl index 72b1463..98150cc 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -15,30 +15,22 @@ snmp-server community "public" Operator ;--- Heure/date time timezone 60 time daylight-time-rule Western-Europe -{%- for server in additionals.ntp_servers %} -{%- for interface in server.interface %} -{%- if switch.subnet.0.vlan_id == interface.vlan_id %} -sntp server priority {{ loop.index }} {{ interface.ipv4 }} 4 -{%- if interface.ipv6 %} -sntp server priority {{ loop.index + 1 }} {{ interface.ipv6.0.ipv6 }} 4 -{%- endif %} -{%- endif %} +{%- for ipv4 in settings.switchs_management_utils.ntp_servers.ipv4 %} +sntp server priority {{ loop.index }} {{ ipv4 }} 4 {%- endfor %} +{%- for ipv6 in settings.switchs_management_utils.ntp_servers.ipv6 %} +sntp server priority {{ loop.index + settings.switchs_management_utils.ntp_servers.ipv4|length }} {{ ipv6 }} 4 {%- endfor %} timesync sntp sntp unicast ;--- Misc --- console inactivity-timer 30 ;--- Logs --- -{%- for server in additionals.log_servers %} -{%- for interface in server.interface %} -{%- if switch.subnet.0.vlan_id == interface.vlan_id %} -logging {{ interface.ipv4 }} -{%- if interface.ipv6 %} -logging {{ interface.ipv6.0.ipv6 }} -{%- endif %} -{%- endif %} +{%- for ipv4 in settings.switchs_management_utils.log_servers.ipv4 %} +logging {{ ipv4 }} {%- endfor %} +{%- for ipv6 in settings.switchs_management_utils.log_servers.ipv6 %} +logging {{ ipv6 }} {%- endfor %} ;--- IP du switch --- no ip default-gateway @@ -92,9 +84,11 @@ aaa authentication ssh login public-key none aaa authentication ssh enable public-key none ip ssh ip ssh filetransfer -ip authorized-managers {{ switch.subnet.0.network }} {{ switch.subnet.0.netmask }} access manager -{%- if switch.subnet6 %} -ipv6 authorized-managers {{ switch.subnet6.network }} {{ switch.subnet6.netmask }} access manager +{%- if settings.switchs_management_utils.subnet %} +ip authorized-managers {{ settings.switchs_management_utils.subnet.0.network }} {{ settings.switchs_management_utils.subnet.0.netmask }} access manager +{%- endif %} +{%- if settings.switchs_management_utils.subnet6 %} +ipv6 authorized-managers {{ settings.switchs_management_utils.subnet6.network }} {{ settings.switchs_management_utils.subnet6.netmask }} access manager {%- endif %} {%- if additionals.loop_protected %} ;--- Protection contre les boucles --- @@ -104,13 +98,9 @@ loop-protect {{ additionals.loop_protected|join(',') }} {%- endif %} ;--- Serveurs Radius radius-server dead-time 2 -{%- for server in additionals.radius_servers %} -{%- for interface in server.interface %} -{%- if switch.subnet.0.vlan_id == interface.vlan_id %} -radius-server host {{ interface.ipv4 }} key "{{ switch.get_radius_key_value }}" -radius-server host {{ interface.ipv4 }} dyn-authorization -{%- endif %} -{%- endfor %} +{%- for ipv4 in settings.switchs_management_utils.radius_servers.ipv4 %} +radius-server host {{ ipv4 }} key "{{ switch.get_radius_key_value }}" +radius-server host {{ ipv4 }} dyn-authorization {%- endfor %} radius-server dyn-autz-port 3799 ;--- Filtrage mac --- @@ -119,10 +109,8 @@ aaa port-access mac-based addr-format multi-colon no cdp run {%- if additionals.dhcp_snooping_vlans %} ;--- DHCP Snooping --- -{%- for server in additionals.dhcp_servers %} -{%- for interface in server.interface %} -dhcp-snooping authorized-server {{ interface.ipv4 }} -{%- endfor %} +{%- for ipv4 in settings.switchs_management_utils.dhcp_servers.ipv4 %} +dhcp-snooping authorized-server {{ ipv4 }} {%- endfor %} dhcp-snooping vlan {{ additionals.dhcp_snooping_vlans|join(' ') }} dhcp-snooping From 8a4212c101b38093790249426202f7b5e28e1209 Mon Sep 17 00:00:00 2001 From: chirac Date: Thu, 12 Jul 2018 00:02:07 +0200 Subject: [PATCH 15/34] =?UTF-8?q?Check=20si=20le=20provisioning=20est=20ac?= =?UTF-8?q?tiv=C3=A9...=20avant=20de=20l'appliquer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 4d71553..508cdb3 100755 --- a/main.py +++ b/main.py @@ -130,7 +130,7 @@ class Switch: def apply_conf(self): if self.check_and_get_login(): - if self.switch["model"] and self.switch["automatic_provision"] == True: + if self.switch["model"] and self.switch["automatic_provision"] == True and self.settings["provision_switchs_enabled"]: constructor = self.switch["model"]["constructor"].lower() if "hp" in constructor or "aruba" in constructor: self.login_hp() From ab37b30b3cd0139c339388c07779816d5e6888af Mon Sep 17 00:00:00 2001 From: chirac Date: Thu, 12 Jul 2018 01:20:11 +0200 Subject: [PATCH 16/34] Configure les ip sur tous les vlans --- templates/hp.tpl | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index 98150cc..eebed11 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -43,17 +43,17 @@ vlan {{ id }} {%- endif %} {%- if vlan["ports_untagged"] %} untagged {{ vlan["ports_untagged"]|join(',') }} + {%- endif %} + {%- for ipv4, subnet in switch.interfaces_subnet.items() %} + {%- if subnet.0.vlan_id == id %} + ip address {{ ipv4 }}/{{ subnet.0.netmask_cidr }} {%- endif %} - {%- if switch.subnet.0.vlan_id == id %} - ip address {{ switch.ipv4 }}/{{ switch.subnet.0.netmask_cidr }} - {%- else %} - no ip address - {%- endif %} - {%- if switch.subnet.0.vlan_id == id %} - ipv6 address {{ switch.ipv6 }}/{{ switch.subnet6.netmask_cidr }} - {%- else %} - no ipv6 enable + {%- endfor %} + {%- for ipv6, subnet6 in switch.interfaces6_subnet.items() %} + {%- if subnet6.vlan_id == id %} + ipv6 address {{ ipv6 }}/{{ subnet6.netmask_cidr }} {%- endif %} + {%- endfor %} {%- if id in additionals.igmp_vlans %} ip igmp no ip igmp querier From 4bac7c64ddfa2a5b8386580d4d4780529972083a Mon Sep 17 00:00:00 2001 From: chirac Date: Thu, 12 Jul 2018 15:30:05 +0200 Subject: [PATCH 17/34] Ajoute l'option force reboot, reboot le switch pour appliquer les options reboot --- main.py | 1 + 1 file changed, 1 insertion(+) diff --git a/main.py b/main.py index 508cdb3..286caf9 100755 --- a/main.py +++ b/main.py @@ -116,6 +116,7 @@ class Switch: {"ip_address": {"version":"IAV_IP_V4", "octets":self.settings["switchs_management_interface_ip"]}}}, + "is_forced_reboot_enabled": True, } # Nous lançons la requête de type POST. post_restore = requests.post(url_restore, data=json.dumps(data), headers=self.headers) From 827220a50ad5ef3b7035d424730343ded78d4420 Mon Sep 17 00:00:00 2001 From: chirac Date: Thu, 12 Jul 2018 16:53:35 +0200 Subject: [PATCH 18/34] Formatage , et gestion des igmp querier --- main.py | 16 ++++++++++++---- templates/hp.tpl | 32 ++++++++++++++++++++------------ 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/main.py b/main.py index 286caf9..60e9f5e 100755 --- a/main.py +++ b/main.py @@ -70,6 +70,13 @@ class Switch: for vlan in port['get_port_profil']['vlan_tagged']: add_to_vlans(vlans, vlan, port) + for ip, subnet in self.switch["interfaces_subnet"].items(): + vlans[subnet[0]["vlan_id"]].setdefault("ipv4", {}) + vlans[subnet[0]["vlan_id"]]["ipv4"][ip] = subnet + for ipv6, subnet in self.switch["interfaces6_subnet"].items(): + vlans[subnet["vlan_id"]].setdefault("ipv6", {}) + vlans[subnet["vlan_id"]]["ipv6"][ipv6] = subnet + arp_protect_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["arp_protect"]] dhcp_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcp_snooping"]] dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcpv6_snooping"]] @@ -112,10 +119,11 @@ class Switch: data = { "server_type": "ST_TFTP", "file_name": self.get_conf_file_name(), - "tftp_server_address": {"server_address": - {"ip_address": - {"version":"IAV_IP_V4", - "octets":self.settings["switchs_management_interface_ip"]}}}, + "tftp_server_address": { + "server_address": { + "ip_address": { + "version":"IAV_IP_V4", + "octets":self.settings["switchs_management_interface_ip"]}}}, "is_forced_reboot_enabled": True, } # Nous lançons la requête de type POST. diff --git a/templates/hp.tpl b/templates/hp.tpl index eebed11..ce50cf5 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -44,25 +44,33 @@ vlan {{ id }} {%- if vlan["ports_untagged"] %} untagged {{ vlan["ports_untagged"]|join(',') }} {%- endif %} - {%- for ipv4, subnet in switch.interfaces_subnet.items() %} - {%- if subnet.0.vlan_id == id %} - ip address {{ ipv4 }}/{{ subnet.0.netmask_cidr }} - {%- endif %} - {%- endfor %} - {%- for ipv6, subnet6 in switch.interfaces6_subnet.items() %} - {%- if subnet6.vlan_id == id %} - ipv6 address {{ ipv6 }}/{{ subnet6.netmask_cidr }} - {%- endif %} - {%- endfor %} {%- if id in additionals.igmp_vlans %} ip igmp - no ip igmp querier {%- endif %} {%- if id in additionals.mld_vlans %} - no ipv6 mld querier ipv6 mld version 1 ipv6 mld enable {%- endif %} + {%- if vlan.ipv4 %} + {%- for ipv4, subnet in vlan.ipv4.items() %} + ip address {{ ipv4 }}/{{ subnet.0.netmask_cidr }} + {%- endfor %} + {%- else %} + no ip address + {%- endif %} + {%- if vlan.ipv6 %} + {%- for ipv6, subnet6 in vlan.ipv6.items() %} + ipv6 address {{ ipv6 }}/{{ subnet6.netmask_cidr }} + {%- endfor %} + {%- else %} + no ipv6 address + {%- if id in additionals.igmp_vlans %} + no ip igmp querier + {%- endif %} + {%- if id in additionals.mld_vlans %} + no ipv6 mld querier + {%- endif %} + {%- endif %} exit {%- endfor %} ;--- Accès d'administration --- From fae56e6fa66383117dd229e4fad1a62ad3eaee06 Mon Sep 17 00:00:00 2001 From: chirac Date: Thu, 12 Jul 2018 16:55:15 +0200 Subject: [PATCH 19/34] Commentaire --- main.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/main.py b/main.py index 60e9f5e..78d2799 100755 --- a/main.py +++ b/main.py @@ -70,6 +70,7 @@ class Switch: for vlan in port['get_port_profil']['vlan_tagged']: add_to_vlans(vlans, vlan, port) + #Trie les ip par vlan, et les ajoute ainsi que les subnet for ip, subnet in self.switch["interfaces_subnet"].items(): vlans[subnet[0]["vlan_id"]].setdefault("ipv4", {}) vlans[subnet[0]["vlan_id"]]["ipv4"][ip] = subnet @@ -77,6 +78,7 @@ class Switch: vlans[subnet["vlan_id"]].setdefault("ipv6", {}) vlans[subnet["vlan_id"]]["ipv6"][ipv6] = subnet + #Regroupement des options par vlans : dhcp_soop,arp, et dhcpv6, ainsi que igmp, mld , ra-guard et loop_protect arp_protect_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["arp_protect"]] dhcp_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcp_snooping"]] dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcpv6_snooping"]] From 6dd130a9627aa4f01f617923a76c3474ea0316f5 Mon Sep 17 00:00:00 2001 From: chirac Date: Thu, 12 Jul 2018 17:37:48 +0200 Subject: [PATCH 20/34] Gestion du mode SFTP de provision --- main.py | 36 ++++++++++++++++++++++++++---------- templates/hp.tpl | 2 -- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/main.py b/main.py index 78d2799..d26f237 100755 --- a/main.py +++ b/main.py @@ -118,16 +118,32 @@ class Switch: 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":self.settings["switchs_management_interface_ip"]}}}, - "is_forced_reboot_enabled": True, - } + provision_mode = self.settings["switchs_provision"] + if provision_mode == "tftp": + data = { + "server_type": "ST_TFTP", + "file_name": self.get_conf_file_name(), + "tftp_server_address": { + "server_address": { + "ip_address": { + "version":"IAV_IP_V4", + "octets":self.settings["switchs_management_interface_ip"]}}}, + "is_forced_reboot_enabled": True, + } + elif provision_mode == "sftp": + data = { + "server_type": "ST_SFTP", + "file_name": self.get_conf_file_name(), + "tftp_server_address": { + "server_address": { + "ip_address": { + "version":"IAV_IP_V4", + "octets":self.settings["switchs_management_interface_ip"]}}, + "user_name": self.settings["switchs_management_sftp_creds"]["login"], + "password": self.settings["switchs_management_sftp_creds"]["pass"], + }, + "is_forced_reboot_enabled": True, + } # Nous lançons la requête de type POST. post_restore = requests.post(url_restore, data=json.dumps(data), headers=self.headers) diff --git a/templates/hp.tpl b/templates/hp.tpl index ce50cf5..cff6914 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -62,8 +62,6 @@ vlan {{ id }} {%- for ipv6, subnet6 in vlan.ipv6.items() %} ipv6 address {{ ipv6 }}/{{ subnet6.netmask_cidr }} {%- endfor %} - {%- else %} - no ipv6 address {%- if id in additionals.igmp_vlans %} no ip igmp querier {%- endif %} From d2e1b92eb7401a02bc67f2742ff9f55074ad5c30 Mon Sep 17 00:00:00 2001 From: chirac Date: Thu, 12 Jul 2018 17:48:32 +0200 Subject: [PATCH 21/34] README --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 375b681..b39a2ff 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ -## Re2o - DHCP +## Re2o - Switchs config -This service uses Re2o API to generate DHCP leases files +This service uses Re2o API to generate Swicths config files +More info on https://gitlab.federez.net/re2o/switchs/wikis/home ## Requirements * python3 +* python3-jinja2 +* python3-json * requirements in https://gitlab.federez.net/re2o/re2oapi From 57db5abf91072b3187af07312b31bac150066d82 Mon Sep 17 00:00:00 2001 From: grisel-davy Date: Wed, 8 Aug 2018 20:30:55 +0200 Subject: [PATCH 22/34] ajout de l'option --force et prise en compte des regen services --- main.py | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) mode change 100755 => 100644 main.py diff --git a/main.py b/main.py old mode 100755 new mode 100644 index d26f237..33be9bd --- a/main.py +++ b/main.py @@ -10,6 +10,8 @@ import requests import base64 import json +import sys + config = ConfigParser() config.read('config.ini') @@ -29,6 +31,18 @@ ENV = Environment(loader=FileSystemLoader('.')) # Création du template final avec les valeurs contenues dans le dictionnaire "valeurs" - Ces valeurs sont positionnées dans un objet "temp", qui sera utilisé par le moteur, et que l'on retrouve dans le template. +for arg in sys.argv: + if arg=="--force": + sw = Switch() + for switch in all_switchs: + sw.switch = switch + sw.gen_conf_and_write() + try: + sw.apply_conf() + except: + print("Erreur dans l'application de la conf pour " + switch["short_name"]) + + class Switch: def __init__(self): @@ -170,11 +184,17 @@ class Switch: -sw = Switch() -for switch in all_switchs: - sw.switch = switch - sw.gen_conf_and_write() - try: - sw.apply_conf() - except: - print("Erreur dans l'application de la conf pour " + switch["short_name"]) +for service in api_client.list("services/regen/"): + if service['hostname'] == client_hostname and \ + service['service_name'] == 'switchs' and \ + service['need_regen']: + error = False + sw=Switch() + for switch in all_switchs: + sw.switch = switch + sw.gen_conf_and_write() + try: + sw.apply_conf() + except: + error = True + api_client.patch(service['api_url'], data={'need_regen': error}) From 004f9c998b152918e028a24dba3d8f01b957a710 Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Thu, 20 Sep 2018 20:31:47 +0200 Subject: [PATCH 23/34] =?UTF-8?q?L=C3=A8ve=20une=20erreur=20si=20la=20conf?= =?UTF-8?q?ig=20propos=C3=A9e=20ne=20permet=20plus=20de=20joindre=20le=20s?= =?UTF-8?q?witch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index 33be9bd..f87f5bc 100644 --- a/main.py +++ b/main.py @@ -31,16 +31,7 @@ ENV = Environment(loader=FileSystemLoader('.')) # Création du template final avec les valeurs contenues dans le dictionnaire "valeurs" - Ces valeurs sont positionnées dans un objet "temp", qui sera utilisé par le moteur, et que l'on retrouve dans le template. -for arg in sys.argv: - if arg=="--force": - sw = Switch() - for switch in all_switchs: - sw.switch = switch - sw.gen_conf_and_write() - try: - sw.apply_conf() - except: - print("Erreur dans l'application de la conf pour " + switch["short_name"]) + @@ -86,6 +77,8 @@ class Switch: #Trie les ip par vlan, et les ajoute ainsi que les subnet for ip, subnet in self.switch["interfaces_subnet"].items(): + if not subnet[0]["vlan_id"] in vlans: + raise RuntimeError("La config est dangeureuse, le vlan d'administration n'est pas propagé au switch !") vlans[subnet[0]["vlan_id"]].setdefault("ipv4", {}) vlans[subnet[0]["vlan_id"]]["ipv4"][ip] = subnet for ipv6, subnet in self.switch["interfaces6_subnet"].items(): @@ -165,9 +158,12 @@ class Switch: """Génère la conf suivant le bon constructeur et l'écrit""" if self.switch["model"]: constructor = self.switch["model"]["constructor"].lower() - if "hp" in constructor or "aruba" in constructor: - self.gen_conf_hp() - self.write_conf() + try: + if "hp" in constructor or "aruba" in constructor: + self.gen_conf_hp() + self.write_conf() + except RuntimeError: + print("Il y a eu une erreur pour le switch %s, la config proposée n'est pas intègre" % self.switch["short_name"]) def apply_conf(self): if self.check_and_get_login(): @@ -183,12 +179,22 @@ class Switch: f.write(self.conf) +for arg in sys.argv: + if arg=="--force": + sw = Switch() + for switch in all_switchs: + sw.switch = switch + sw.gen_conf_and_write() + try: + sw.apply_conf() + except: + print("Erreur dans l'application de la conf pour " + switch["short_name"]) for service in api_client.list("services/regen/"): if service['hostname'] == client_hostname and \ service['service_name'] == 'switchs' and \ service['need_regen']: - error = False + error = False sw=Switch() for switch in all_switchs: sw.switch = switch From 1aeb14ddc603a44704ad20f5835aa73826ff3998 Mon Sep 17 00:00:00 2001 From: Antoine Vintache Date: Fri, 21 Sep 2018 00:01:04 +0200 Subject: [PATCH 24/34] Code intelligent pour print la version du switch --- templates/hp.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index cff6914..9a3e30b 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -1,4 +1,4 @@ -; {{ switch.model.reference }}A Configuration Editor; Created on release #{{ switch.model.firmware }} +; {%- if switch.model.reference[-1]=='A' %} {{ switch.model.reference }}{%- else %} {{ switch.model.reference }}A{%- endif %} Configuration Editor; Created on release {%- if switch.model.firmware[0]=='#' %} {{ switch.model.firmware }}{%- else %} #{{ switch.model.firmware }}{%- endif %} hostname "{{ switch.short_name }}" ; Generated on {{ date_gen }} by re2o From 57583da6b64e9d1138f1f681fc1e9f85ad46465f Mon Sep 17 00:00:00 2001 From: Antoine Vintache Date: Thu, 27 Sep 2018 18:03:35 +0200 Subject: [PATCH 25/34] specifie la vitesse du port --- templates/hp.tpl | 3 +++ 1 file changed, 3 insertions(+) diff --git a/templates/hp.tpl b/templates/hp.tpl index 9a3e30b..43915f1 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -172,6 +172,9 @@ interface {{ port.port }} {%- if not port.get_port_profil.dhcpv6_snooping %} dhcpv6-snooping trust {%- endif %} + {%- if port.get_port_profil.speed != "auto" %} + speed-duplex {{port.get_port_profil.speed}} + {%- endif %} no lacp exit {%- endfor %} From 7e1e3ae347af4038e0ee70ea2550f657fe534e17 Mon Sep 17 00:00:00 2001 From: chirac Date: Sat, 13 Oct 2018 14:58:48 +0200 Subject: [PATCH 26/34] Add LICENSE --- LICENSE | 339 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 339 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..60055dd --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + switchs + Copyright (C) 2018 Re2o + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. From 4d0219b691b53057ebd53765971fa216999e6255 Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Sat, 13 Oct 2018 22:46:46 +0200 Subject: [PATCH 27/34] Fix port profile + add datetime to template --- main.py | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/main.py b/main.py index f87f5bc..6178080 100644 --- a/main.py +++ b/main.py @@ -9,7 +9,7 @@ from jinja2 import Environment, FileSystemLoader import requests import base64 import json - +import datetime import sys config = ConfigParser() @@ -32,7 +32,6 @@ ENV = Environment(loader=FileSystemLoader('.')) # Création du template final avec les valeurs contenues dans le dictionnaire "valeurs" - Ces valeurs sont positionnées dans un objet "temp", qui sera utilisé par le moteur, et que l'on retrouve dans le template. - class Switch: @@ -53,7 +52,7 @@ class Switch: def preprocess_hp(self): """Prérempli certains valeurs renvoyées directement à jinja, pour plus de simplicité""" - + def add_to_vlans(vlans, vlan, port, tagged=True): if not vlan['vlan_id'] in vlans: if not tagged: @@ -69,10 +68,10 @@ class Switch: vlans = dict() for port in self.switch['ports']: - if port['get_port_profil']['vlan_untagged']: - add_to_vlans(vlans, port['get_port_profil']['vlan_untagged'], port, tagged=False) - if port['get_port_profil']['vlan_tagged']: - for vlan in port['get_port_profil']['vlan_tagged']: + if port['get_port_profile']['vlan_untagged']: + add_to_vlans(vlans, port['get_port_profile']['vlan_untagged'], port, tagged=False) + if port['get_port_profile']['vlan_tagged']: + for vlan in port['get_port_profile']['vlan_tagged']: add_to_vlans(vlans, vlan, port) #Trie les ip par vlan, et les ajoute ainsi que les subnet @@ -91,8 +90,8 @@ class Switch: dhcpv6_snooping_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["dhcpv6_snooping"]] igmp_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["igmp"]] mld_vlans = [vlan["vlan_id"] for vlan in self.all_vlans if vlan["mld"]] - ra_guarded = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['ra_guard']] - loop_protected = [str(port['port']) for port in self.switch['ports'] if port['get_port_profil']['loop_protect']] + ra_guarded = [str(port['port']) for port in self.switch['ports'] if port['get_port_profile']['ra_guard']] + loop_protected = [str(port['port']) for port in self.switch['ports'] if port['get_port_profile']['loop_protect']] self.additionals = {'ra_guarded' : ra_guarded, 'loop_protected' : loop_protected, 'vlans' : vlans, 'arp_protect_vlans' : arp_protect_vlans, 'dhcp_snooping_vlans' : dhcp_snooping_vlans, 'dhcpv6_snooping_vlans' : dhcpv6_snooping_vlans, 'igmp_vlans' : igmp_vlans, 'mld_vlans': mld_vlans} @@ -100,7 +99,7 @@ class Switch: def gen_conf_hp(self): """Génère la config pour ce switch hp""" self.preprocess_hp() - self.conf = self.hp_tpl.render(switch=self.switch, settings=self.settings, additionals=self.additionals) + self.conf = self.hp_tpl.render(switch=self.switch, settings=self.settings, additionals=self.additionals, date_gen=datetime.datetime.now()) def check_and_get_login(self): """Récupère les login/mdp du switch, renvoie false si ils sont indisponibles""" @@ -113,9 +112,9 @@ class Switch: 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"], + "userName" : self.creds_dict["id"], "password" : self.creds_dict["pass"] } get_cookie = requests.post(url_login, data=json.dumps(payload_login)) @@ -202,5 +201,5 @@ for service in api_client.list("services/regen/"): try: sw.apply_conf() except: - error = True + error = True api_client.patch(service['api_url'], data={'need_regen': error}) From cc221f9d03636d57618da7606ea931a62743e5c5 Mon Sep 17 00:00:00 2001 From: detraz Date: Sun, 30 Dec 2018 11:17:03 +0100 Subject: [PATCH 28/34] Get port -> get_port_profile + supprime l'unauth vlan id --- templates/hp.tpl | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index 43915f1..e86e692 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -138,20 +138,19 @@ ipv6 ra-guard ports {{ additionals.ra_guarded|join(',')}} {%- endif %} ;--- Config des prises --- {%- for port in switch.ports %} -{%- if port.get_port_profil.radius_type == "802.1X" %} +{%- if port.get_port_profile.radius_type == "802.1X" %} aaa port-access authenticator {{ port.port }} -{%- if port.get_port_profil.mac_limit %} -aaa port-access authenticator {{ port.port }} client-limit {{ port.get_port_profil.mac_limit }} +{%- if port.get_port_profile.mac_limit %} +aaa port-access authenticator {{ port.port }} client-limit {{ port.get_port_profile.mac_limit }} {%- endif %} aaa port-access authenticator {{ port.port }} logoff-period 3600 {%- endif %} -{%- if port.get_port_profil.radius_type == "MAC-radius" %} +{%- if port.get_port_profile.radius_type == "MAC-radius" %} aaa port-access mac-based {{ port.port }} -{%- if port.get_port_profil.mac_limit %} -aaa port-access mac-based {{ port.port }} addr-limit {{ port.get_port_profil.mac_limit }} +{%- if port.get_port_profile.mac_limit %} +aaa port-access mac-based {{ port.port }} addr-limit {{ port.get_port_profile.mac_limit }} {%- endif %} aaa port-access mac-based {{ port.port }} logoff-period 3600 -aaa port-access mac-based {{ port.port }} unauth-vid 1 {%- endif %} interface {{ port.port }} {%- if port.state %} @@ -160,20 +159,20 @@ interface {{ port.port }} disable {%- endif %} name "{{ port.pretty_name }}" - {%- if port.get_port_profil.flow_control %} + {%- if port.get_port_profile.flow_control %} flow-control {%- endif %} - {%- if not port.get_port_profil.dhcp_snooping %} + {%- if not port.get_port_profile.dhcp_snooping %} dhcp-snooping trust {%- endif %} - {%- if not port.get_port_profil.arp_protect %} + {%- if not port.get_port_profile.arp_protect %} arp-protect trust {%- endif %} - {%- if not port.get_port_profil.dhcpv6_snooping %} + {%- if not port.get_port_profile.dhcpv6_snooping %} dhcpv6-snooping trust {%- endif %} - {%- if port.get_port_profil.speed != "auto" %} - speed-duplex {{port.get_port_profil.speed}} + {%- if port.get_port_profile.speed != "auto" %} + speed-duplex {{port.get_port_profile.speed}} {%- endif %} no lacp exit From d24bb7cc268ff7fba1f5df441dc7ee2026a7bd2a Mon Sep 17 00:00:00 2001 From: detraz Date: Sun, 30 Dec 2018 11:29:00 +0100 Subject: [PATCH 29/34] =?UTF-8?q?Liste=20des=20r=C3=A9cursifs=20fournies?= =?UTF-8?q?=20par=20rest/re2O?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- templates/hp.tpl | 3 +++ 1 file changed, 3 insertions(+) diff --git a/templates/hp.tpl b/templates/hp.tpl index e86e692..8345b92 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -93,6 +93,9 @@ ip ssh filetransfer {%- if settings.switchs_management_utils.subnet %} ip authorized-managers {{ settings.switchs_management_utils.subnet.0.network }} {{ settings.switchs_management_utils.subnet.0.netmask }} access manager {%- endif %} +{%- for ipv4 in settings.switchs_management_utils.dns_recursive_servers.ipv4 %} +ip dns server-address priority {{ loop.index }} {{ ipv4 }} +{%- endfor %} {%- if settings.switchs_management_utils.subnet6 %} ipv6 authorized-managers {{ settings.switchs_management_utils.subnet6.network }} {{ settings.switchs_management_utils.subnet6.netmask }} access manager {%- endif %} From 6af90e4ff9093084d6411df07cc61fb876461c22 Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Fri, 4 Jan 2019 11:55:57 +0100 Subject: [PATCH 30/34] Generation des modules avec re2o dans conf hp --- templates/hp.tpl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/templates/hp.tpl b/templates/hp.tpl index 8345b92..edf146f 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -2,6 +2,10 @@ hostname "{{ switch.short_name }}" ; Generated on {{ date_gen }} by re2o +;--- General --- +{%- for slot, ref in switch.list_modules %} +module {{ slot }} type {{ ref }} +{%- endfor %} ;--- Snmp --- {%- if switch.switchbay.name %} snmp-server location "{{ switch.switchbay.name }}" From 6702e2cc418d15f98f5ed8d5638fdd3f3b2f32de Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Fri, 4 Jan 2019 11:57:45 +0100 Subject: [PATCH 31/34] No tls sur adm --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 6178080..03f86b4 100644 --- a/main.py +++ b/main.py @@ -19,7 +19,7 @@ api_hostname = config.get('Re2o', 'hostname') api_password = config.get('Re2o', 'password') api_username = config.get('Re2o', 'username') -api_client = Re2oAPIClient(api_hostname, api_username, api_password) +api_client = Re2oAPIClient(api_hostname, api_username, api_password, use_tls=False) client_hostname = socket.gethostname().split('.', 1)[0] From 58eb2bad6257acdccf94e13e88257d3afc2dbcbe Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Fri, 4 Jan 2019 11:58:59 +0100 Subject: [PATCH 32/34] =?UTF-8?q?D=C3=A9but=20configuration=20pour=20maj?= =?UTF-8?q?=20automatique=20des=20switchs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 75 insertions(+), 10 deletions(-) diff --git a/main.py b/main.py index 03f86b4..1b5be8a 100644 --- a/main.py +++ b/main.py @@ -121,6 +121,10 @@ class Switch: cookie = get_cookie.json()['cookie'] self.headers = {"Cookie" : cookie} + def test(self): + url_info = "http://" + self.switch["ipv4"] + "/rest/v4/system/status/global_info" + get = requests.get(url_info, headers=self.headers) + def apply_conf_hp(self): """Apply config restore via rest""" url_restore = "http://" + self.switch["ipv4"] + "/rest/v4/system/config/cfg_restore" @@ -177,17 +181,78 @@ class Switch: with open("generated/" + self.get_conf_file_name(), 'w+') as f: f.write(self.conf) - -for arg in sys.argv: - if arg=="--force": - sw = Switch() - for switch in all_switchs: - sw.switch = switch - sw.gen_conf_and_write() + def upgrade(self): + """Met à jour le switch en fonction du constructeur""" + if self.switch["model"]: + constructor = self.switch["model"]["constructor"].lower() try: - sw.apply_conf() - except: - print("Erreur dans l'application de la conf pour " + switch["short_name"]) + if "hp" in constructor or "aruba" in constructor: + self.get_firmware_hp() + if self.primary_firmware < self.switch["firmware"]: + self.upgrade_hp() + # self.reboot_hp() + except RuntimeError: + print("Il y a eu une erreur pour la mise à jour du switch" + self.switch["short_name"]) + + def get_firmware_hp(self): + # L'URI est positionnée dans une variable + url_cli = "http://" + self.switch["ipv4"] + "/rest/v4/cli" + # On crée le dictionnaire avec la clé "cmd" et la valeur de la commande convertit en châine + data = { + "cmd": "show flash" + } + # On lance la requête avec le dictionnaire convertit en JSON et l'entête de session + post_cmd = requests.post(url_cli, data= json.dumps(data), headers=self.headers) + # On récupère le résultat de la requête, qui est décodé de base64, puis décodé en utf-8 + result_decode = base64.b64decode(post_cmd.json()['result_base64_encoded']).decode('utf-8') + self.primary_firmware = result_decode.split('Secondary')[0].split()[-1] + self.secondary_firmware = result_decode.split('Boot')[0].split()[-1] + + + def upgrade_hp(self): + """Update switch via rest""" + + # On spécifie l'URI pour le transfert de fichier + url_file = "http://" + self.switch["ipv4"] + "/rest/v4/file-transfer" + + # On crée le dictionnaire comportant les informations nécessaires (actions / URL / etc...) + data = { + "file_type":"FTT_FIRMWARE", + "url":"http://" + self.settings["switchs_management_interface_ip"] + "/" + self.switch["firmware"] + ".swi", + "action":"FTA_DOWNLOAD", + "boot_image": "BI_PRIMARY_IMAGE" + } + + # On lance la requête au format POST + post_file = requests.post(url_file, data=json.dumps(data), headers=self.headers) + + + def reboot_hp(slef): + url_reboot = "http://" + self.switch["ipv4"] + "/rest/v4/system/reboot" + + data = { + "action":"reload" + } + + post_reboot = requests.post(url_reboot, data=json.dumps(data), headers=self.headers) + + +if "--force" in sys.argv: + sw = Switch() + for switch in all_switchs: + sw.switch = switch + sw.gen_conf_and_write() + try: + sw.apply_conf() + except: + print("Erreur dans l'application de la conf pour " + switch["short_name"]) + +if "--upgrade" in sys.argv: + sw = Switch() + for switch in all_switchs: + sw.switch = switch + sw.upgrade() + for service in api_client.list("services/regen/"): if service['hostname'] == client_hostname and \ From 8defc92ecc70b065b3a3ceb75d2fb9ba399c3861 Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Sat, 23 May 2020 01:57:09 +0200 Subject: [PATCH 33/34] =?UTF-8?q?Adapte=20=C3=A0=20la=20nouvelle=20version?= =?UTF-8?q?=20de=20re2o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 1b5be8a..860c7cd 100644 --- a/main.py +++ b/main.py @@ -76,10 +76,10 @@ class Switch: #Trie les ip par vlan, et les ajoute ainsi que les subnet for ip, subnet in self.switch["interfaces_subnet"].items(): - if not subnet[0]["vlan_id"] in vlans: + if not subnet["vlan_id"] in vlans: raise RuntimeError("La config est dangeureuse, le vlan d'administration n'est pas propagé au switch !") - vlans[subnet[0]["vlan_id"]].setdefault("ipv4", {}) - vlans[subnet[0]["vlan_id"]]["ipv4"][ip] = subnet + vlans[subnet["vlan_id"]].setdefault("ipv4", {}) + vlans[subnet["vlan_id"]]["ipv4"][ip] = subnet for ipv6, subnet in self.switch["interfaces6_subnet"].items(): vlans[subnet["vlan_id"]].setdefault("ipv6", {}) vlans[subnet["vlan_id"]]["ipv6"][ipv6] = subnet From cd89d28a6088f11631ed680a488f9541fc9b7d33 Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Tue, 4 Aug 2020 23:27:34 +0200 Subject: [PATCH 34/34] Fix re2o 2.8+ Compat --- templates/hp.tpl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/templates/hp.tpl b/templates/hp.tpl index edf146f..394874b 100644 --- a/templates/hp.tpl +++ b/templates/hp.tpl @@ -57,7 +57,7 @@ vlan {{ id }} {%- endif %} {%- if vlan.ipv4 %} {%- for ipv4, subnet in vlan.ipv4.items() %} - ip address {{ ipv4 }}/{{ subnet.0.netmask_cidr }} + ip address {{ ipv4 }}/{{ subnet.netmask_cidr }} {%- endfor %} {%- else %} no ip address @@ -95,7 +95,7 @@ aaa authentication ssh enable public-key none ip ssh ip ssh filetransfer {%- if settings.switchs_management_utils.subnet %} -ip authorized-managers {{ settings.switchs_management_utils.subnet.0.network }} {{ settings.switchs_management_utils.subnet.0.netmask }} access manager +ip authorized-managers {{ settings.switchs_management_utils.subnet.network }} {{ settings.switchs_management_utils.subnet.netmask }} access manager {%- endif %} {%- for ipv4 in settings.switchs_management_utils.dns_recursive_servers.ipv4 %} ip dns server-address priority {{ loop.index }} {{ ipv4 }} @@ -111,7 +111,7 @@ loop-protect {{ additionals.loop_protected|join(',') }} {%- endif %} ;--- Serveurs Radius radius-server dead-time 2 -{%- for ipv4 in settings.switchs_management_utils.radius_servers.ipv4 %} +{%- for ipv4 in switch.get_radius_servers.ipv4 %} radius-server host {{ ipv4 }} key "{{ switch.get_radius_key_value }}" radius-server host {{ ipv4 }} dyn-authorization {%- endfor %}