recuperalier des info alias mail et generation du fichier aliases de postfix

This commit is contained in:
grisel-davy 2018-07-17 23:51:20 +02:00
parent d2e1b92eb7
commit 3ade345c95
4 changed files with 24 additions and 334 deletions

View file

164
main.py
View file

@ -9,6 +9,7 @@ from jinja2 import Environment, FileSystemLoader
import requests import requests
import base64 import base64
import json import json
import os.path
config = ConfigParser() config = ConfigParser()
config.read('config.ini') config.read('config.ini')
@ -21,160 +22,23 @@ api_client = Re2oAPIClient(api_hostname, api_username, api_password)
client_hostname = socket.gethostname().split('.', 1)[0] client_hostname = socket.gethostname().split('.', 1)[0]
all_switchs = api_client.list("switchs/ports-config/") all_users = api_client.list("mail/alias")
# Création de l'environnement Jinja # Création de l'environnement Jinja
ENV = Environment(loader=FileSystemLoader('.')) env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('templates/list')
aliases_rendered = template.render(data=all_users)
fichier = open('generated/aliases','w')
# 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. if os.path.isfile('aliases_local'): # if a local aliases file exist, add it's content at the beginning
local = open('aliases_local','r')
for line in local.readlines():
fichier.write(line)
local.close()
fichier.write(aliases_rendered)
fichier.close()
class Switch: print('done')
def __init__(self):
self.additionnal = None
self.all_vlans = api_client.list("machines/vlan/")
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
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"
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:
if not tagged:
vlans[vlan['vlan_id']]['ports_untagged'].append(str(port['port']))
else:
vlans[vlan['vlan_id']]['ports_tagged'].append(str(port['port']))
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']:
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
for ipv6, subnet in self.switch["interfaces6_subnet"].items():
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"]]
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']]
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, 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"""
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"
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)
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 apply_conf(self):
if self.check_and_get_login():
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()
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:
f.write(self.conf)
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"])

View file

@ -1,184 +0,0 @@
; {{ switch.model.reference }}A Configuration Editor; Created on release #{{ switch.model.firmware }}
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
snmpv3 user "re2o"
snmpv3 group ManagerPriv user "re2o" sec-model ver3
snmp-server community "public" Operator
;--- Heure/date
time timezone 60
time daylight-time-rule Western-Europe
{%- 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 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
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 id in additionals.igmp_vlans %}
ip igmp
{%- endif %}
{%- if id in additionals.mld_vlans %}
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 %}
{%- 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 ---
no telnet-server
{%- if switch.web_management_enabled %}
{%- 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 %}
{%- if switch.rest_enabled %}
rest-interface
{%- endif %}
aaa authentication ssh login public-key none
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
{%- 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 ---
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 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 ---
aaa port-access mac-based addr-format multi-colon
;--- Bricoles ---
no cdp run
{%- if additionals.dhcp_snooping_vlans %}
;--- DHCP Snooping ---
{%- 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
{%- 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" %}
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 }}
{%- endif %}
aaa port-access authenticator {{ port.port }} logoff-period 3600
{%- endif %}
{%- if port.get_port_profil.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 }}
{%- 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 %}
enable
{%- else %}
disable
{%- endif %}
name "{{ port.pretty_name }}"
{%- if port.get_port_profil.flow_control %}
flow-control
{%- endif %}
{%- if not port.get_port_profil.dhcp_snooping %}
dhcp-snooping trust
{%- endif %}
{%- if not port.get_port_profil.arp_protect %}
arp-protect trust
{%- endif %}
{%- if not port.get_port_profil.dhcpv6_snooping %}
dhcpv6-snooping trust
{%- endif %}
no lacp
exit
{%- endfor %}
;--- Configuration comptabilisation RADIUS ---
aaa accounting network start-stop radius
aaa accounting session-id unique
aaa accounting update periodic 240
;--- Filtre de protocole ---
filter multicast 01005e0000fb drop all
filter multicast 3333000000fb drop all

10
templates/list Normal file
View file

@ -0,0 +1,10 @@
# Liste d'association alias:addresse des users
{%- for user in data -%}
{%- for alias in user.get_mail_aliases -%}
{%- if user.redirection -%}
{{alias.valeur}}:{{ user.get_mail }}
{%- else -%}
{{alias.valeur}}:{{ user.pseudo }}
{% endif %}
{% endfor %}
{% endfor %}