Skip to content

Instantly share code, notes, and snippets.

@jul
Last active March 11, 2020 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jul/54d272d5ebc540877282aa582627b63e to your computer and use it in GitHub Desktop.
Save jul/54d272d5ebc540877282aa582627b63e to your computer and use it in GitHub Desktop.
ldap 2 dhcpd
#!/usr/bin/env python3
from bla import *
from ldap3 import *
from contextlib import contextmanager
from sys import argv
import ipaddress as ip
netmask = lambda s: str(ip.IPv4Network("0.0.0.0/%s" % s.dhcpNetmask).netmask)
@contextmanager
def nop(full=False):
try:
yield
except Exception as e:
if not full and not isinstance(e, ldap3.core.exceptions.LDAPCursorError):
raise(e)
def sons(entry):
ldap.search(
entry.entry_dn,
"(objectClass=*)",
search_scope = LEVEL,
attributes=["structuralObjectClass", "*"]
)
return ldap.entries
BI = " "
prelude = dict(
dhcpService = "",
dhcpClass = """class "%(cn)s" {""",
dhcpSubnet = "subnet %(cn)s netmask %(netmask)s {",
dhcpGroup = """group {""",
dhcpPool = """pool {""",
dhcpDnsZone = """zone %(cn)s {""",
dhcpSharedNetwork = """shared-network "%(cn)s" {""",
dhcpHost = """host %(cn)s {""",
dhcpTSigKey = """key %(cn)s {""",
)
def pe(entry, indent = 0):
dec = indent and BI * indent or ""
arg = dict(
cn = entry.cn,
)
with nop(full=True):
arg["netmask"] = netmask(entry)
print(dec + prelude[str(entry.structuralObjectClass)] % arg)
dec = BI * (indent + 1)
ac = lambda s : print(dec + s + (";", "")[s.startswith("if ") or s.endswith(";")])
with nop(True):
ac("range %(dhcpRange)s" % entry)
with nop(full=True):
list(map(lambda e : ac("# " +e), entry.dhcpComments))
with nop(full=True):
ac("primary %(dhcpDnsZoneServer)s" % entry)
if hasattr(entry, "dhcpKeyDN"):
ac("key %s" % get(str(entry.dhcpKeyDN)).cn)
with nop(True):
ac("hardware %(dhcpHWAddress)s" % entry)
with nop(full=True):
ac("algorithm %(dhcpKeyAlgorithm)s" % entry)
ac("secret %s" % entry.dhcpKeySecret.encode("ascii"))
with nop():
list(map(ac, entry.dhcpStatements))
with nop():
list(map(lambda e: ac("option " + e), entry.dhcpOption))
for son in sons(entry):
pe(son, indent+1)
dec = indent and BI * indent or ""
if indent >= 0:
print(dec + "}")
print()
base = "cn=DHCP,dc=example"
ldap.search(base,"(objectClass=*)", search_scope=BASE, attributes=["structuralObjectClass", "*"])
root=ldap.entries[0]
pe(root, indent=-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment