From 541efd79f64d86809a2cadcda7841b081ed0ebf1 Mon Sep 17 00:00:00 2001 From: Frank Brehm Date: Fri, 12 Jun 2020 12:09:24 +0200 Subject: [PATCH] Adding method get_dhcp_ip() to Cobbler class --- lib/cr_vmware_tpl/cobbler.py | 40 +++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/lib/cr_vmware_tpl/cobbler.py b/lib/cr_vmware_tpl/cobbler.py index ef0027f..daddc53 100644 --- a/lib/cr_vmware_tpl/cobbler.py +++ b/lib/cr_vmware_tpl/cobbler.py @@ -16,6 +16,7 @@ import pipes import json import hashlib import textwrap +import ipaddress from json import JSONDecodeError @@ -37,7 +38,7 @@ from .config import CrTplConfiguration from .xlate import XLATOR -__version__ = '0.4.11' +__version__ = '0.5.1' LOG = logging.getLogger(__name__) @@ -61,6 +62,8 @@ class Cobbler(BaseHandler): A handler class for executing cobbler actions. """ + dhcpd_leases_file = Path('/var') / 'lib' / 'dhcpd' / 'dhcpd.leases' + # ------------------------------------------------------------------------- def __init__( self, appname=None, verbose=0, version=__version__, base_dir=None, @@ -728,6 +731,41 @@ class Cobbler(BaseHandler): self.ensure_remote_directory(remote_dir) self.ensure_remote_file(auth_keys_file, remote_file, check_parent=False) + # ------------------------------------------------------------------------- + def get_dhcp_ip(self, mac_address): + + mac = mac_address.lower() + LOG.debug(_("Trying to get IP of MAC address {!r} given by DHCP ...").format(mac)) + all_leases = self.get_remote_filecontent(self.dhcpd_leases_file) + + cur_ip = None + assigments = {} + re_lease_start = re.compile(r'^\s*lease\s+((?:\d{1,3}:){3}\d{1,3})\s+', re.IGNORECASE) + re_mac = re.compile( + r'^\s*hardware\s+ethernet\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})\s*;', re.IGNORECASE) + + for line in all_leases.splitlines(): + match = re_lease_start.match(line) + if match: + try: + ip = ipaddress.ip_address(match.group(1)) + cur_ip = str(ip) + except ValueError as e: + msg = _("Found invalid IP address {ip!r} in leases file: {err}").format( + ip=match.group(1), err=e) + LOG.error(msg) + continue + + match = re_mac.match(line) + if match: + found_mac = match.group(1).lower() + if cur_ip: + assigments[found_mac] = cur_ip + continue + + if mac in assigments: + return assigments[mac] + return None # ============================================================================= if __name__ == "__main__": -- 2.39.5