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
git clone https://gitlab.com/abvavgjeremy/pythonactivedirectory.git
virtualenv -p python3 venv
Activate the venv
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
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 email@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].
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 firstname.lastname@example.org -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.