]> Frank Brehm's Git Trees - pixelpark/create-vmware-tpl.git/commitdiff
Adding method get_dhcp_ip() to Cobbler class
authorFrank Brehm <frank.brehm@pixelpark.com>
Fri, 12 Jun 2020 10:09:24 +0000 (12:09 +0200)
committerFrank Brehm <frank.brehm@pixelpark.com>
Fri, 12 Jun 2020 10:09:24 +0000 (12:09 +0200)
lib/cr_vmware_tpl/cobbler.py

index ef0027f455157b5a089528249dc79f69a384b66d..daddc53cd0c5de6548631c85d38e8393404c3ac4 100644 (file)
@@ -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__":