Here is another work on Python that I want to share with the community.
To learn Python here are the references:
- Introduction to Python
- https://leanpub.com/PowerShell-to-Python – ebook
- https://www.pluralsight.com/ – Core Python (Video training)
Download and install python on your windows machine
For IDE you can use Pycharm Community edition
Let’s now get back to the topic and export attributes of users from Active Directory.
With PowerShell We utilize Active directory Module for all AD related operations.
For python there are different libraries for different products, I have used ldap3 in this example script.
https://pypi.org/project/ldap3/
Install it on your machine using pip install ldap3

Download the Python script from below link:
https://github.com/VikasSukhija/Python/blob/main/ExportADAttributes.py
Update the below code that starts at line number 86 – logs and variables
#########################code#########################
# log and variables
log_file = create_file(“logs”, “export_ad”, “log”)
report_file = create_file(“report”, “export_ad”, “csv”)
base_dn = “DC=labtest,DC=com”
domain_controller = “DC”
admin_userid = “labtest\\vikas”
admin_password = “Password”
obj_filter = “(&(objectClass=user)(objectCategory=person)(!(useraccountcontrol:1.2.840.113556.1.4.803:=2)))”
#########################code#########################
Objfilter – it is ldap filter for Enabled user accounts. (you can update as per your requirements)
Also note the code at line 106 and code in CSV section as that is important for export.
#################Code##########################
with Connection(Server(domain_controller, port=636, use_ssl=True),
auto_bind=AUTO_BIND_NO_TLS,
read_only=True,
check_names=True,
user=admin_userid, password=admin_password) as c:
c.extend.standard.paged_search(search_base=base_dn,
search_filter=obj_filter,
search_scope=SUBTREE,
attributes={'sAMAccountName', 'userPrincipalName', 'mail', 'mobile', 'title',
'department'},
get_operational_attributes=True,
paged_size=1500,
generator=False)
write_log("Fetched Ad Attributes", log_file)
write_log("Export to CSV file", log_file)
with open(report_file, mode='w', newline='', encoding='utf-8') as csv_file:
fieldnames = ['sAMAccountName', 'userPrincipalName', 'mail', 'mobile', 'title',
'department']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for user in c.entries:
write_log("exporting..." + str(user["sAMAccountName"]), log_file)
writer.writerow(
{'sAMAccountName': user["sAMAccountName"], 'userPrincipalName': user["userPrincipalName"],
'mail': user["mail"], 'mobile': user["mobile"], 'title': user["title"],
'department': user["department"]})
#################Code##########################
Run the python file as: python ExportADAttributes.py from the directory where script is stored.

Script will auto create logs/report folder for logs and report storage.

Stay tuned for more Python Sample codes.
Thanks for reading and downloading…
Tech Wizard