LDAP/LDIF Parsing

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Feb 1 17:49:15 EST 2007


Cruelemort a écrit :
> All,
> 
> I am hoping someone would be able to help me with a problem. I have an
> LDAP server running on a linux box, this LDAP server contains a
> telephone list in various groupings, the ldif file of which is -
> 
(snip)
> 
> I am creating a python client program that will display the telephone
> list in the same directory structure as is on the LDAP server (i.e. it
> starts with buttons of all the groups, when you click on a group it
> comes up with buttons of all the numbers or groups available, and you
> can continually drill down).
> 
> I was wondering the best way to do this? I have installed and used the
> python-ldap libraries and these allow me to access and search the
> server, but the searches always return a horrible nesting of lists,
> tuples and dictionaries, below is an example of returning just one
> record -
> 
> ('dc=example,dc=com', {'objectClass': ['top', 'dcObject',
> 'organization'], 'dc': ['example'], 'o': ['Example Organisation']})

What's your problem ? That's exactly what your ldap record should look 
like. A (base_dn, record) tuple, where the record is a dict of 
attribute_name:[values, ...]

> Basically i think i need to parse the search results to create objects

Q&D wrapper:

class LdapObject(object):
   def __init__(self, ldapentry):
     self.dn, self._record = ldapentry

   def __getattr__(self, name):
     try:
       data = self._record[name]
     except KeyError:
       raise AttributeError(
         "object %s has no attribute %s" % (self, name)
        )
     else:
       # all LDAP attribs are multivalued by default,
       # even when the schema says they are monovalued
       if len(data) == 1:
          return data[0]
       else:
          return data[:]

   def isa(self, objectClass):
     return objectClass in self.objectClass:

root = LdapObject(
   ('dc=example,dc=com',
    {'objectClass': ['top', 'dcObject','organization'],
     'dc': ['example'],
     'o': ['Example Organisation']}
   ))

root.o
=> 'Example Organisation'
root.objectClass
=> ['top', 'dcObject','organization']
root.isa('organization')
=> True

FWIW, I once started writing an higher-level LDAP api (kind of an 
Object-LDAP Mapper...) using descriptors for ldap attribute access, but 
I never finished the damned thing, and it's in a very sorry state. I'll 
have to get back to it one day...

>  and build the python buttons around this, but i was hoping someone
> would be able to point me in the correct direction of how to do this?
> Is there a parser available? 

cf above.



More information about the Python-list mailing list