Fetching enabled AD users from a domain controller with Python 3 – Ahazu.com

Fetching enabled AD users from a domain controller with Python 3

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

username = "domainuser"
password = "password"
server_name = "DomainControllerHostname"
domain_name = "domain.local"
ldap_base="dc=domain,dc=local"

# Perform a paged search (unpaged has a limit of 5000)

entries = conn.extend.standard.paged_search(
    search_base=ldap_base,
    search_filter='(&(objectclass=person)(company=companyname)(userAccountControl=512))',
    # User Account Control explanation:
    ## 512 - Normal account (512),
    ## 514 - Disable account (2 + 512),
    ## 66048 - Normal account + dont expire password (65536 + 512).
    attributes=['cn', 'displayName','company','userAccountControl','mail'],
    paged_size=100
)

#Inserting all data into a dataframe
import pandas as pd
num = 0
skipnum = 0
df = pd.DataFrame(columns=['cn','displayName','userAccountControl','mail'])

# Loop through entries and put the data into dataframe
for entry in entries:
    try:
        if df.empty == False:
            cn = entry['attributes']['cn']
            displayName = entry['attributes']['displayName']
            uac = entry['attributes']['userAccountControl']
            mail = entry['attributes']['mail']
            df = df.append(pd.DataFrame({'cn' : [cn], 'displayName' : [displayName], 'userAccountControl', [uac], 'mail' : [mail]}, columns=['cn','displayName','userAccountControl','mail']))
else:
            #Creates new DF
            cn = entry['attributes']['cn']
            displayName = entry['attributes']['displayName']
            uac = entry['attributes']['userAccountControl']
            mail = entry['attributes']['mail']
            df = pd.DataFrame({'cn' : [cn], 'displayName' : [displayName], 'userAccountControl', [uac], 'mail' : [mail]}, columns=['cn','displayName','userAccountControl','mail'])
        num += 1
    except NameError as error:
        cn = entry['attributes']['cn']
        displayName = entry['attributes']['displayName']
    except KeyError as error:
        print("Error: skipping entry")
        skipnum += 1
print(num + " entries")
print(skipnum + " entries skipped)

Leave a comment

Your email address will not be published. Required fields are marked *