Skip to content

Instantly share code, notes, and snippets.

@tasoseng
Created March 26, 2021 22:27
Show Gist options
  • Save tasoseng/9a8c426cfff99e71e8609f56a08b1b27 to your computer and use it in GitHub Desktop.
Save tasoseng/9a8c426cfff99e71e8609f56a08b1b27 to your computer and use it in GitHub Desktop.
def getLdapAttribute(uid, attribute):
import sys
SERVER=ldapserver.example.com
PORT=636
BIND_DN='uid=binder,dc=example,dc=com'
BIND_PW='changeme'
baseDN = "dc=example,dc=com"
if sys.version_info[0] == 3:
from ldap3 import Server, Connection, ALL
retrieveAttributes = [ attribute ]
searchFilter = "(uid={})".format(uid)
server = Server(SERVER, port = PORT, use_ssl = True, get_info=ALL)
conn = Connection(server, BIND_DN, BIND_PW, auto_bind=True)
result = conn.search(baseDN, searchFilter, attributes=[attribute])
if result:
entry = conn.entries[0]
return entry.entry_dn, entry[attribute].value
else:
import ldap
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = [ attribute ]
searchFilter = "uid={}".format(uid)
try:
l = ldap.initialize('ldaps://{}'.format(SERVER))
l.simple_bind_s(BIND_PW)
results = l.search_s(baseDN, searchScope, searchFilter, retrieveAttributes)
if results:
dn, result = results[0]
if attribute in result.keys():
return dn, result[attribute][0]
else:
return dn, ""
except ldap.LDAPError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment