[Python Patterns] Working with Microsoft Active Directory

Using your Python super powers to work with Microsoft's Active Directory.

At the office, like many companies, we use Microsoft's Active Directory. As a Mac user and admin of some services it really helps to be able to work with Active Directory on a daily basis with Python.

There are four scripts, but they work with two different Python modules.  The python-ldap module and the ldap3 module.  I use the ldap3 module as it has a nice interface for authenticating with NTLM and working with groups. I used these scripts as a basis to create some nice Lambdas in AWS at the office, maybe they will help you.


Clone the repo

GitHub - ephergent/PythonActiveDirectory
Contribute to ephergent/PythonActiveDirectory development by creating an account on GitHub.
git clone https://github.com/bitsofjeremy/pythonactivedirectory.git

Setup Virtualenv

virtualenv -p python3 venv

Activate the venv

source venv/bin/activate

Install Requirements

pip install -r requirements.txt

Edit and copy env-example to .env

[Note: You will need a Active Directory user with correct permissions]

cp env-example .env

Source .env

source .env

Run it


Returns a dictionary with email, first name, and last name.  This can be extended to any AD attribute you desire.

python get_ad_user_by_email.py -e user@example.com


This script grabs a user's info from AD via their NT object. It is meant to be imported into other scripts and run get_user(member object) to pull info from AD.


Takes a group and spits out a user list of emails. It is meant to be imported into other scripts and run get_users(ldap_base_dn) to pull a list of emails from an AD group [Think mail list].

[Requires: get_user_by_ad_obj.py]


This one uses the ldap3 module to add a user to the specified group. It finds the user via email, adds them to a provided group DN.

python add_user_to_ldap_group.py -e user@example.com -l "cn=MyGroup,ou=All Users,dc=ad,dc=example,dc=com"

[Note: Your user in .env needs to be the 'native owner' of the group, not just a admin]

My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot.  They are written to be a quick starting point for future projects so I do not need to type as much.