Created
June 2, 2014 00:37
-
-
Save futureimperfect/795e6586ad7e9fc4e529 to your computer and use it in GitHub Desktop.
Complex LDAP Queries with python-ldap
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
import ldap | |
import sys | |
LDAP_URI = 'ldap://ldap.example.com' | |
SEARCH_BASE = 'ou=Example,dc=example,dc=com' | |
QUERY = '(&(nickname=M*)(employeeType=fulltime)(|(!(departmentNumber=5*))(loginShell=/bin/bash)))' | |
def ldap_search(ldap_uri, base, query): | |
''' | |
Perform an LDAP query. | |
''' | |
emails = [] | |
try: | |
l = ldap.initialize(ldap_uri) | |
l.protocol_version = ldap.VERSION3 | |
search_scope = ldap.SCOPE_SUBTREE | |
retrieve_attributes = None | |
ldap_result_id = l.search( | |
base, | |
search_scope, | |
query, | |
retrieve_attributes | |
) | |
result_set = [] | |
while 1: | |
result_type, result_data = l.result(ldap_result_id, 0) | |
if (result_data == []): | |
break | |
else: | |
if result_type == ldap.RES_SEARCH_ENTRY: | |
result_set.append(result_data) | |
if len(result_set) == 0: | |
print('No results found.') | |
return | |
count = 0 | |
for i in range(len(result_set)): | |
for entry in result_set[i]: | |
try: | |
email = entry[1]['mail'][0] | |
count += 1 | |
emails.append(email) | |
except: | |
pass | |
except ldap.LDAPError, e: | |
print('LDAPError: %s.' % e) | |
finally: | |
l.unbind_s() | |
print emails | |
def main(): | |
ldap_search(LDAP_URI, SEARCH_BASE, QUERY) | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment