Split entries from LDAP

Michael Ströder michael at stroeder.com
Mon Oct 13 18:04:17 CEST 2008


Lars wrote:
> I'm trying
> to create a script that creates a variable list (just a txt file to be
> included in bash scripts) with hosts from LDAP.

What exactly do you want to do? I'd recommend against passing a custom
text format around. Use either LDIF or CSV with decent modules.

> The file will include
> some static entries and the hosts based on 'cn', 'ipHostNumber' and I
> might as well set the 'description' as commen,t when the list from
> LDAP is created.

Better give an example.

> I got all the entries in the variable "raw_res" and I now got some
> doubts on how to split each value up in every entry.

> 	raw_res = l.search_s( basedn, ldap.SCOPE_SUBTREE, filter, attrs )

This is the synchronous method which might not be suitable for large
result sets.

> for I in range(len(raw_res)):
> 	print I, ": ",

In a simple case you could do:

for dn,entry in raw_res:
  print dn,entry # or whatever

But in LDAPv3 search results can also be search continuation (or
sometimes called referrals). E.g. AD makes use of them when search from
the domain level (without subordinate ou). In python-ldap these are
returned as a 2-tuple (None,StringType with LDAP URL).

So be prepared to handle the case that in the example above dn is None
and entry is a LDAP URL pointing to another server or part of the DIT.

On my test server:

>>>
pprint.pprint(l.search_s('ou=Testing,dc=...',ldap.SCOPE_ONELEVEL,attrlist=['cn']))
[('uid=anna,ou=Testing,dc=stroeder,dc=de',
  {'cn': ['Anna Blume']}),
 ('cn=Fred Feuerstein,ou=Testing,dc=stroeder,dc=de',
  {'cn': ['Fred Feuerstein']}),
 (None, ['ldap://ldap.openldap.org/dc=openldap,dc=org??base'])]

Ciao, Michael.



More information about the Python-list mailing list