pythonactive-directorypyad

Change how PyAD searches for Users


I am working on creating a python script that can connect to AD and search for user attributes such as (name, email, location, email, extension). Currently I am searching users by CN to find their AD account. The problem I am running into is that some users have a middle initial in their CN but not on their display name. Is it possible to search a user by their display name or sAMAccount name to then be able to pull the attributes from their AD account?

The script is below and works fine when search by CN.

from tkinter import N
from pyad import*
from pyad import adquery
from pyad import aduser
from nameparser import HumanName
from nameparser.config import CONSTANTS

from StatesFun import StatesL

#connecting to AD
pyad.set_defaults (ldap_server="", Adminusername="", password="")
UserName = input("Please input the username of the user requesting a DAT account, (first lastname, not case sensitive)\n")

#Searching user in AD
user = pyad.aduser.ADUser.from_cn(UserName)

#searching for user attributes
#pop takes element out of list and converts to string 
nameAD = user.get_attribute("cn")
name = nameAD.pop(0)
emailAD = user.get_attribute("mail")
email = emailAD.pop(0)
stAD = user.get_attribute("st")
st = stAD.pop(0)
extAD = user.get_attribute("telephoneNumber")
ext = extAD.pop(0)

#Parses name for initials
def initials(full_name):
  initial=""
  if (len(full_name) == 0):
   return
    
  first_middle_last = full_name.split(" ")
  for name in first_middle_last:
    initial=initial+name[0].upper()+""
  return initial

#Splits First / Last Name into own text values
Hname = HumanName(name)
Hname = Hname

#Parses TQL Username from Email
DatUsrNameAD = (email.split('@'))
DatUsrName = DatUsrNameAD.pop(0)

print(DatUsrName)
print(Hname.first)
print(Hname.last)
print(initials(name))
print(StatesL(st))
print(ext)
print(email)

Solution

  • You could use something like this to search by SamAccountName. Would just need to update the base_dn to match you company's domain settings.

    import pyad.adquery
    
    q = pyad.adquery.ADQuery()
    
    user = 'abc123'
    
    q.execute_query(
        attributes = ["departmentNumber"],
        where_clause = f"SamAccountName = '{user}'",
        base_dn="DC=*,DC=*,DC=*"
    )
    
    for row in q.get_results():
        dept = row["departmentNumber"]
        print (dept)