The following code demo's one way you can query active directory, translating a username to an email address. Code is derived from this stackexchange post
To run, requires the python module ldap3
pip install ldap3
The code needs to authenticate against the active directory. The secrets used to perform the authentication are contained in the environment variables:
LDAP_USER= LDAP_PASSWD= LDAP_HOST=
import os
import ldap3
def parseHost(host):
'''
translates a host like
google.com
to
DC=google,DC=com
'''
hostList = host.split('.')
newLists = []
hostStr = ''
for part in hostList:
newLists.append(f'DC={part}')
print(f"host string: {','.join(newLists)}")
return ','.join(newLists)
def LDAPAdQuery(inputUserName):
'''
:param inputUserName: active directory username who's email is that you want to
retrieve
:return the email that corresponds with the email.
'''
user = os.environ['LDAP_USER']
password = os.environ['LDAP_PASSWD']
host = os.environ['LDAP_HOST']
server = ldap3.Server(host)
connection = ldap3.Connection(server, user=user, password=password)
connection.bind()
hostStr = parseHost(host)
connection.search(search_base=hostStr, search_filter='(&(objectClass=user)(mailNickname='+inputUserName.upper()+'))', search_scope='SUBTREE', attributes='*')
outEmail = connection.response[0]['attributes']['userPrincipalName']
print(f'email: {outEmail}')
return outEmail
if __name__ == '__main__':
# inputUser is the username who's email you want to retrieve, example, 'glafleur'
inputUser = <username>
email = LDAPAdQuery(inputUser)
print(f"input user: {inputUser}, email is: {email}")