Skip to content

Instantly share code, notes, and snippets.

@franTarkenton
Last active May 7, 2020 01:49
Show Gist options
  • Select an option

  • Save franTarkenton/674b96e2f05acc9cf54e4008ed2056d1 to your computer and use it in GitHub Desktop.

Select an option

Save franTarkenton/674b96e2f05acc9cf54e4008ed2056d1 to your computer and use it in GitHub Desktop.

Description

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

Requirements

To run, requires the python module ldap3

pip install ldap3

Code

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}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment