diff --git a/main.py b/main.py index eb00682..b7a75f1 100755 --- a/main.py +++ b/main.py @@ -18,22 +18,35 @@ api_password = config.get('Re2o', 'password') api_username = config.get('Re2o', 'username') def regen_dhcp(api_client): - host_mac_ip = {} + """Genere les fichiers de zone du DHCP, par extension et par plage d'ip""" + host_mac_ip_ext = {} + host_mac_ip_type = {} - for hmi in api_client.list("dhcp/hostmacip/"): - if hmi['ip_type'] not in host_mac_ip.keys(): - host_mac_ip[hmi['ip_type']] = [] - host_mac_ip[hmi['ip_type']].append((hmi['hostname'], - hmi['extension'], - hmi['mac_address'], - hmi['ipv4'])) + api_res = api_client.list("dhcp/hostmacip/") + + build_hmi(host_mac_ip_ext, api_res, 'extension') + build_hmi(host_mac_ip_type, api_res, 'ip_type') template = ("host {hostname}{extension} {{\n" " hardware ethernet {mac_address};\n" " fixed-address {ipv4};\n" "}}") - for ip_type, hmi_list in host_mac_ip.items(): + generate_file(template, host_mac_ip_ext, "dhcp") + generate_file(template, host_mac_ip_type, "dhcp.ip_type.") + +def build_hmi(host_mac_ip, api_res, key): + for hmi in api_res: + if hmi[key] not in host_mac_ip.keys(): + host_mac_ip[hmi[key]] = [] + host_mac_ip[hmi[key]].append((hmi['hostname'], + hmi['extension'], + hmi['mac_address'], + hmi['ipv4'])) + + +def generate_file(template, host_mac_ip, file_prefix): + for key, hmi_list in host_mac_ip.items(): dhcp_leases_content = '\n\n'.join(template.format( hostname=hostname, extension=extension, @@ -41,10 +54,13 @@ def regen_dhcp(api_client): ipv4=ipv4 ) for hostname, extension, mac_address, ipv4 in hmi_list) - filename = path+'/generated/dhcp.{ip_type}.list'.format(ip_type=ip_type) + filename = path+'/generated/{file_prefix}{key}.list'.format( + key=key, + file_prefix=file_prefix) with open(filename, 'w+') as f: f.write(dhcp_leases_content) + def reload_server(): """Relance le serveur DHCP.""" try: