I am trying to query email addresses and aliases from AD. Sometimes I get no entries back from an email even though the email exists in AD. I ran a loop 100 times to test an email and 7 times I got no entries. I am running python 3.10.7 and ldap3 2.9.1 . Does anyone know if there is an existing bug or can it be because my VM is not part of the domain?
# Search active directory for the user to see if they are still with the company
def search_active_directory(email, domain, ad_password, ad_username):
missing = 0
# Connect to domain
domain_connect = Connection(Server(domain, get_info=ALL),user=ad_username, password=ad_password, auto_bind=True)
# Combine the parts into the full search filter
search_filter = create_search_filter(email)
# Define the attributes
attributes = ['mail', 'proxyAddresses', 'userPrincipalName', 'targetAddress']
the_emails = []
for x in range(100):
search_base = "DC=amer, DC=com"
domain_connect.search(search_base, search_filter, SUBTREE, attributes=attributes)
if len(domain_connect.entries) == 0:
missing += 1
return missing
# Help function to return the string for the search filter
def create_search_filter(email):
user_account_control = "(!(userAccountControl:1.2.840.113556.1.4.803:=2))"
mail = f"(mail={email})"
proxy_addresses = f"(proxyAddresses=*{email}*)"
user_principal_name = f"(userPrincipalName=*{email}*)"
target_address = f"(targetAddress=*{email}*)"
return f"(&{user_account_control}(|{mail}{proxy_addresses}{user_principal_name}{target_address}))"