Skip to content

Instantly share code, notes, and snippets.

@grenade
Created August 23, 2013 10:42
Show Gist options
  • Save grenade/6317926 to your computer and use it in GitHub Desktop.
Save grenade/6317926 to your computer and use it in GitHub Desktop.
Lookup user attributes in LDAP with Python
def user_info(username):
#todo: move these parameters to config
ldap_host = 'example.com'
ldap_port = 389
ldap_base_dn = 'OU=DK,DC=example,DC=com'
ldap_bind_dn = 'CN=<removed>,OU=DK,DC=example,DC=com'
ldap_bind_pw = '<removed>'
ldap_attr_uid = 'sAMAccountName'
ldap_attr_forename = 'givenName'
ldap_attr_surname = 'sn'
ldap_attr_display_name = 'displayName'
ldap_attr_department = 'department'
ldap_attr_employee_type = 'employeeType'
ldap_attr_email = 'mail'
l = ldap.initialize('ldap://%s:%s' % (ldap_host, ldap_port))
l.simple_bind_s(ldap_bind_dn, ldap_bind_pw)
r = l.search_s(base=ldap_base_dn,
scope=ldap.SCOPE_SUBTREE,
filterstr='(%s=%s)' % (ldap_attr_uid, username),
attrlist=[
ldap_attr_forename,
ldap_attr_surname,
ldap_attr_email,
ldap_attr_display_name,
ldap_attr_employee_type,
ldap_attr_department])
if r:
dn, e = r[0]
return {
'dn': dn,
'forename': e[ldap_attr_forename][0],
'surname': e[ldap_attr_surname][0],
'email': e[ldap_attr_email][0],
'display_name': e[ldap_attr_display_name][0],
'department': e[ldap_attr_department][0],
'employee_type': e[ldap_attr_employee_type][0]}
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment