How to read the contents of active directory using python-ldap?

Sharadhi Ballal picture Sharadhi Ballal · Nov 16, 2012 · Viewed 11.8k times · Source

My script is like this:

import ldap, sys
server = 'ldap://my_server'
l = ldap.initialize(server)
dn="myname@mydomain"
pw = "password"
l.simple_bind_s(dn,pw)
ldap.set_option(ldap.OPT_REFERRALS,0)
print "valid"

I am using Python 2.7 on windows.

Is there any method to read or get the contents of active directory?

Answer

Vyktor picture Vyktor · May 13, 2014

You can do quite a lot also using win32com.client (which I had trouble finding documentation for). For example I've needed to resolve user email knowing his ADS_NAME_TYPE_NT4 formatted name (doman\jonjoe).

First of all you need to convert it to ADS_NAME_TYPE_1779 format (CN=Jeff Smith,CN=users,DC=Fabrikam,DC=com):

name_resolver = win32com.client.Dispatch(dispatch='NameTranslate')
name_resolver.Set(3, 'domain\\jonjoe')
ldap_query = 'LDAP://{}'.format(name_resolver.Get(1))

Once you have that you can simply call GetObject():

ldap = win32com.client.GetObject(ldap_query)
print(ldap.Get('mail'))

Tested with Python 3.2.5