Wednesday, September 21, 2016

Python script to connect to LDAP and write a list of users to a text file

Download python ldap 64bit here
http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap
and install using pip

The code helps write a list of users to a text file. 3 nested loops for affiliation, last name, and first name help arrange the user list in the corresponding order and at the same time reduce the size of the return results from the query.

The content in result_data looks like the following (some attributes were already removed)

[('uid=xxxxxxxx,ou=people,dc=examples,dc=edu', {'departmentNumber': ['12345'], 'displayName': ['Doe, John'], 'cn': ['John Doe'], , 'l': ['Orlando'], 'telephoneNumber': ['+1 800 000 0000'], 'eduPersonAffiliation': ['employee', 'staff'], 'street': ['Ocean Avenue'], 'sn': ['Doe'], 'mail': ['john.doe@examples.edu'], 'postalAddress': ['Ocean Avenue'], 'givenName': ['John']})]

import ldap

try:

    l = ldap.open("ldap.examples.edu")

    l.protocol_version = ldap.VERSION3

except ldap.LDAPError, e:

    print e


baseDN = "dc=examples,dc=edu"

searchScope = ldap.SCOPE_SUBTREE

## retrieve all attributes

retrieveAttributes = None



text_file = open("userlist.txt", "w")

affiliation = ['faculty','staff']

try:

    for affl in affiliation:

        for ln in range(ord('A'), ord('Z') + 1):

            for fn in range(ord('A'), ord('Z') + 1):

                searchFilter = "(&(eduPersonAffiliation=" + affl + ")(sn=" + chr(ln) + "*)(givenName=" + chr(fn) + "*))"

              

                ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)

                result_set = []

                while 1:

                    result_type, result_data = l.result(ldap_result_id, 0)

                    if (result_data == []):

                        break

                    else:

                        uid = result_data[0][0].split(',')[0].split('=')[1]

                        if 'displayName' in result_data[0][1]:

                            displayName = result_data[0][1]['displayName'][0]

                        else:

                            displayName = ""

                        if 'departmentNumber' in result_data[0][1]:

                            departmentNumber = result_data[0][1]['departmentNumber'][0]

                        else:

                            departmentNumber = ""           

                        if 'mail' in result_data[0][1]:

                            mail = result_data[0][1]['mail'][0]

                        else:

                            mail = ""

                        if 'telephoneNumber' in result_data[0][1]:

                            telephoneNumber = result_data[0][1]['telephoneNumber'][0].replace("+1","").replace(" ","")

                            telephoneNumber = "(" + telephoneNumber[:3] + ")" + " " + telephoneNumber[3:6] + "-" + telephoneNumber[6:]

                        else:

                            telephoneNumber = ""

                      

                        text_file.write(uid.ljust(16) + displayName.ljust(30) + departmentNumber.ljust(9) + mail.ljust(200) + telephoneNumber.ljust(14) + "\n")

      

except ldap.LDAPError, e:

    print e

  

text_file.close()