1

I am trying to get a list of usernames using a list of emails in pyad. I know I can get emails from the usernames:

user = aduser.ADUser.from_cn('username').mail

But I was wondering if there was a way to do the reverse.

userfriendly
  • 363
  • 1
  • 4
  • 12

3 Answers3

1

I know this is too late to respond to this thread, but this may help some other who are looking for such solution ..

You can use where clause with specific condition just like below to fetch the required attribute values.

Please note :- you need to specify the attributes you needed in the attributes list

attributes=["employeeID", "username"]

like above to get the desired attributes in your output.

import pyad.adquery

q = pyad.adquery.ADQuery()

user_email_id = 'emailID@company.com'

q.execute_query(
    attributes=["employeeID", "username"],
    where_clause="userPrincipalName = '{}'".format(user_email_id),
    base_dn="OU=*****,OU=*****,DC=****,DC=*****,DC=*****"
)

for row in q.get_results():
    print(row.get('username'))
puneetShanbhag
  • 739
  • 6
  • 7
0

I'm not familiar with pyad, but if user is a string and we can say with confidence that an email is just the username with ".mail" appended to it then we can just do...

user = "mBobgus.email"
print(user.rstrip(".email"))  


mBobgus

The .rstrip() string method just removed the specified string from the right side of the string.

KuboMD
  • 684
  • 5
  • 16
  • 1
    Unfortunately, the usernames follow the format "LastName_Firstinitial" whereas the email is "FirstName.LastName@org.org". I could potentially manipulate the email addresses to be usernames, but there are several inconsistencies in the nomenclature. (For instance, the email will have a middle initial that won't appear in the username, etc.). – userfriendly Dec 05 '18 at 19:19
  • 1
    I see. I guess you need an AD-specific answer then, which I cannot provide. Sorry! – KuboMD Dec 05 '18 at 19:20
0
q = pyad.adsearch.ADQuery()
q.execute_query(
attributes=["mail"]
where_clause = "objectClass = '*'"
base_dn = "ou=XXXXXX, ou=XXXX, DC=XXXXXX, DC=XXXXX")

adoutpout = []
for row in q.get_results():
    adouput.append(row["mail")
adoutput = [x for x  in adouput if x != None]
print(adoutput)

this will get whatever address is in the Email field in AD. You may be looking for the userPrincipalName, in which case just add it to the attributes and row append.