Commit f5821e93 authored by root's avatar root
Browse files

Initial commit

#!/bin/env python3
import argparse
import configparser
import getpass
import ipaddress
import json
import logging
import os
import subprocess
import sys
import jinja2
import re2oapi
path = os.path.dirname(os.path.abspath(__file__))
logger = logging.getLogger('dhcp')
handler = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter('%(asctime)s - %(name)s[%(process)d] - %(levelname)s - %(message)s')
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generate DHCP",
parser.add_argument("-e", "--export", help="Exporte la configuration des dhcps sur la sortie standard", action="store_true")
parser.add_argument("-p", "--re2o-password", help="Demande le mot de passe de l'utilisateur re2o", action="store_true")
parser.add_argument("-q", "--quiet", help="Diminue la verbosité des logs (à spécifier plusieurs fois pour diminuer la verbosité)", action='count', default=0)
parser.add_argument("-r", "--re2o-server", help="Nom du serveur re2o à contacter", type=str, default=None)
parser.add_argument("-u", "--re2o-user", help="Utilisateur re2o", type=str, default=None)
parser.add_argument("-v", "--verbose", help="Augmente la verbosité des logs (à spécifier plusieurs fois pour augmenter la verbosité)", action='count', default=0)
args = parser.parse_args()
verbosity = args.verbose - args.quiet
if verbosity <= -1:
elif verbosity == 0:
elif verbosity >= 1:
logger.setLevel(logging.DEBUG)"Reading configuration")
with open(os.path.join(path, "dhcp.json")) as config_file:
config = json.load(config_file)
logger.debug("Loaded {}".format(config))"Reading Re2o configuration")
re2o_config = configparser.ConfigParser(), 're2o-config.ini'))
if args.re2o_server is not None:
api_hostname = args.re2o_server
api_hostname = re2o_config.get('Re2o', 'hostname')
if args.re2o_user is not None:
api_username = args.re2o_user
api_username = re2o_config.get('Re2o', 'username')
if args.re2o_password:
api_password = getpass.getpass('Re2o password: ')
api_password = re2o_config.get('Re2o', 'password')"Connecting to Re2o")
api_client = re2oapi.Re2oAPIClient(api_hostname, api_username, api_password, use_tls=False)"Querying Re2o")
machines_api = api_client.list("dhcp/hostmacip")
machines_pool = { extension : [] for extension in config['extensions'] }
for machine in machines_api:
if machine['extension'][1:] not in config['extensions'] or \
any(key not in machine.keys() for key in ['ipv4', 'mac_address', 'hostname']) :
extension = machine['extension'][1:]
'hostname': machine['hostname'],
'mac': machine['mac_address'],
'ip': machine['ipv4']
for extension, machines in machines_pool.items():
with open(os.path.join(path, 'templates', 'list.j2')) as list_template:
template = jinja2.Template(
if args.export:
print(template.render(machines=machines, extension=extension))
with open(os.path.join(path, 'generated', f"dhcp.{extension}.list"), 'w') as generated:
generated.write(template.render(machines=machines, extension=extension))
hostname = re2o
username = firewall
password = changeme
from .re2oapi import *
from .client import ApiSendMail, Re2oAPIClient
from . import exceptions
__all__ = ['Re2oAPIClient', 'ApiSendMail', 'exceptions']
This diff is collapsed.
class APIClientGenericError(ValueError):
template = "{}"
def __init__(self, *data): = data
self.message = self.template.format(*data)
super(APIClientGenericError, self).__init__(self.message)
class InvalidCredentials(APIClientGenericError):
template = "The credentials for {}@{} are not valid."
class PermissionDenied(APIClientGenericError):
template = "The {} request to '{}' was denied for {}."
class TokenFileNotFound(APIClientGenericError):
template = "Token file at {} not found."
class TokenFileNotReadable(APIClientGenericError):
template = "Token file at {} is not a JSON readable file."
class TokenNotInTokenFile(APIClientGenericError):
template = "Token for {}@{} not found in token file ({})."
{% for machine in machines %}
host {{ machine.hostname }}.{{ extension }} {
hardware ethernet {{ machine.mac }}
fixed-address {{ machine.ip }}
{% endfor %}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment