Skip to content

Instantly share code, notes, and snippets.

@buchi
Last active June 21, 2017 14:41
Show Gist options
  • Save buchi/9691565 to your computer and use it in GitHub Desktop.
Save buchi/9691565 to your computer and use it in GitHub Desktop.
from ldap.controls import SimplePagedResultsControl
import ldap
import csv
try:
# python-ldap 2.4
LDAP_CONTROL_PAGED_RESULTS = ldap.CONTROL_PAGEDRESULTS
PYTHON_LDAP_24 = True
except AttributeError:
# python-ldap 2.3
LDAP_CONTROL_PAGED_RESULTS = ldap.LDAP_CONTROL_PAGE_OID
PYTHON_LDAP_24 = False
host = 'ldap://example.com:389'
bind_dn = '[email protected]'
bind_pw = 'secret'
base_dn = 'dc=example,dc=com'
filter_ = '(objectCategory=Person)'
# Show only activate users
# filter_ = '(!(userAccountControl=66050))'
# filter_ = '(objectClass=*)'
attrs = [
'sAMAccountName',
'givenname',
'sn',
'mail',
'description',
'telephonenumber',
'homephone',
'mobile',
]
page_size = 1000
conn = ldap.initialize(host)
conn.simple_bind_s(bind_dn, bind_pw)
if PYTHON_LDAP_24:
lc = SimplePagedResultsControl(size=page_size, cookie='')
else:
lc = SimplePagedResultsControl(LDAP_CONTROL_PAGED_RESULTS,
True,
(page_size, ''),)
is_last_page = False
results = []
while not is_last_page:
msgid = conn.search_ext(base_dn,
ldap.SCOPE_SUBTREE,
filter_,
attrs,
serverctrls=[lc])
res = conn.search_s(base_dn, ldap.SCOPE_SUBTREE, filter_, attrs)
rtype, rdata, rmsgid, serverctrls = conn.result3(msgid)
results.extend(rdata)
pctrls = [c for c in serverctrls
if c.controlType == LDAP_CONTROL_PAGED_RESULTS]
if pctrls:
if PYTHON_LDAP_24:
cookie = pctrls[0].cookie
if cookie:
lc.cookie = cookie
else:
is_last_page = True
else:
cookie = pctrls[0].controlValue[1]
if cookie:
lc.controlValue[1] = cookie
else:
is_last_page = True
else:
print "Server ignores paged results control (RFC 2696)."
is_last_page = True
csv_file = open('users.csv', 'wb')
csv_writer = csv.writer(csv_file,
delimiter=';',
quotechar='"',
quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(attrs)
for dn, entry in results:
row = []
for attr in attrs:
if attr in entry:
row.append(entry[attr][0])
else:
row.append('')
csv_writer.writerow(row)
csv_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment