Sunday, January 7, 2018

Connecting to Active Directory using Python

This post speaks about connecting to Active Directory using python - 

python provides the ldap3 for python which can be used to connect to active directory servers. The below code will take the userid and password of the user and check it against active directory to verify the user and his credentials.

import sys
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError

server_name = 'your server name or ipaddress'
domain_name = 'your domain name'
user_name = <username of the user>
password = <password of the user>


format_string = '{:40}   {}'

server = Server(server_name, get_info=ALL)
conn = Connection(server, user='{}\\{}'.format(domain_name, user_name), password=)
if not conn.bind():
    print("error")
else:
    print("sucessful")
   
print(format_string.format('Group', 'Description'))

#CN to get the only the users and not the servers
conn.search('CN=users,dc=domain_name,dc=com'.format(domain_name), search_filter='(&(samAccountName=' + '' + '))',search_scope=SUBTREE,attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])
for e in sorted(conn.entries):
    try:
        desc = e.description
    except LDAPCursorError:
        desc = ""
    print(format_string.format(str(e.name), desc))


This code will connect and print. However this code is not production ready code as you can see there is no exception handling, and the values are more or less hard coded in the code.

No comments:

Post a Comment