Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save born2discover/5bc7a8e97b07dde273a7489d871c37ab to your computer and use it in GitHub Desktop.
Save born2discover/5bc7a8e97b07dde273a7489d871c37ab to your computer and use it in GitHub Desktop.
Python-LDAP: find the groups a user is a member of.
LDAP_SERVER = "ldaps://my-ldap-server.com/"
LDAP_BASE = "dc=my-ldap-server,dc=com"
def users_ldap_groups(uid):
""" Returns a list of the groups that the uid is a member of.
Returns False if it can't find the uid or throws an exception.
It's up to the caller to ensure that the UID they're using exists!
"""
logger.debug("uid: ", uid)
# ignore certificate errors
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
l = ldap.initialize(LDAP_SERVER)
# this search for all objectClasses that user is in.
# change this to suit your LDAP schema
search_filter='(|(&(objectClass=*)(member=uid=%s,cn=users,cn=accounts,dc=my-ldap-server,dc=com)))' % uid
try:
# this returns the groups!
results = l.search_s(LDAP_BASE, ldap.SCOPE_SUBTREE, search_filter, ['cn',])
logger.debug('%s groups: %s' % (uid, results) )
return results
except ldap.NO_SUCH_OBJECT as e:
logger.error("{}:{}unable to lookup uid {} on LDAP server {}: {}".format(__file__, sys._getframe().f_code.co_name, uid, LDAP_SERVER, e))
return False
except Exception as e: # some other error occured
logger.error("{}:{}: other error occurred looking up {} in LDAP: {}".format(__file__, sys._getframe().f_code.co_name,uid,e))
return False
# shouldn't get here, but if we do, we don't have any results!
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment