I’ve been searching around for a native Python 3 package that would allow me to do some LDAP queries against a Microsoft Active Directory (AD) controller and I found ldap3 (formally known as python3-ldap but that got confusing with python-ldap which is a Python 2 package by the folks at OpenLDAP).

I had some dialogue today via email with the nice guy Giovanni Cannata that manages the package. He pointed me to some good information about how to get a simple search running from the package. What I really like about the package is that it has methods to output queries as json and additionally it is strictly RFC compliant; something I wish more people would take on when it comes to making their packages ubiquitous and standard oriented. The package has good documentation too which is something that truly gives me the warm and fuzzies enough to actually want to spend the time to use a package. Use Active Directory Certificate Services to make a DC LDAPS capable.

On to the code (Hitting a 2008 R2 DC with SSL):


from ldap3 import Server, \
    Connection, \
    AUTO_BIND_NO_TLS, \
    SUBTREE, \
    ALL_ATTRIBUTES

def get_ldap_info(u):
    with Connection(Server('<Server IP Address>', port=636, use_ssl=True),
                    auto_bind=AUTO_BIND_NO_TLS,
                    read_only=True,
                    check_names=True,
                    user='Domain\\Username', password='password') as c:

        c.search(search_base='CN=Users,DC=domain,DC=local',
                 search_filter='(&(samAccountName=' + u + '))',
                 search_scope=SUBTREE,
                 attributes=ALL_ATTRIBUTES,
                 get_operational_attributes=True)

    print(c.response_to_json())
    print(c.result)

get_ldap_info('username')

A note on SSL through LDAPS on a domain controller:

Some applications authenticate with Active Directory Domain Services (AD DS) through simple BIND. As simple BIND exposes the users’ credentials in clear text, use of Kerberos is preferred. If simple BIND is necessary, using SSL/TLS to encrypt the authentication session is strongly recommended.