Skip to content

Instantly share code, notes, and snippets.

@JosefJezek
Last active April 23, 2022 07:49
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save JosefJezek/5644296 to your computer and use it in GitHub Desktop.
Save JosefJezek/5644296 to your computer and use it in GitHub Desktop.
Export Users from Active Directory / LDAP to CSV file with Python
#!/usr/bin/python
# http://www.packtpub.com/article/python-ldap-applications-ldap-opearations
# sudo apt-get install python-ldap
import ldap
host = 'ldap://example.com:389'
dn = 'ldap@example.com'
pw = 'secret'
base_dn = 'cn=users,dc=example,dc=com'
filter = 'memberOf=cn=workers,cn=users,dc=example,dc=com'
# Show only activated users
# filter = '(&(memberOf=cn=workers,cn=users,dc=example,dc=com)(!(userAccountControl=66050)))'
attrs = ['sAMAccountName', 'givenname', 'sn', 'mail', 'description', 'telephonenumber', 'homephone', 'mobile']
con = ldap.initialize( host )
# Bind to the server
con.simple_bind_s( dn, pw )
res = con.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs )
# Close the connection
con.unbind()
# Print the returned dictionary
print res
for i in res:
print i[1]['givenname'], i[1]['sn']
# TODO: save as csv file
@filipisaci
Copy link

How can I to contribute with your code?

I made a code based in your code for python3 and I export: users, groups and members of groups.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment