Last active
March 11, 2020 19:55
-
-
Save jul/54d272d5ebc540877282aa582627b63e to your computer and use it in GitHub Desktop.
ldap 2 dhcpd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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