Search code examples
pythonldap

How to find an element in a dict inside tuple?


I have made a bit of a mess, so it is the first time I try to fetch data from a Microsoft AD. I have succeeded in this, but now I want to compare the list of names in the AD with a list I have in my database. But I find it hard to just get the name of the user from the output so I can compare the two lists. So I just want to fetch data for all users in the ad-group 'testuser', 'testuser2' for example.

Output from ldap_result

('CN=testuser,OU=Users,OU=nnittest,DC=nnittest,DC=com', {'givenName': [b'testuser'], 'sAMAccountName': [b'testuser']})
('CN=testuser2,OU=Users,OU=nnittest,DC=nnittest,DC=com', {'givenName': [b'testuser2'], 'sAMAccountName': [b'testuser2']})

Code and connection

LDAP_SERVER = 'ldap://****' 
BASE_DN = 'OU=test,dc=test,dc=com' #base dn to search in
LDAP_LOGIN = 'Admin' 
LDAP_PASSWORD = '*****' 

connect = ldap.initialize(LDAP_SERVER) 
connect.set_option(ldap.OPT_REFERRALS, 0) # to search the object and all its descendants
connect.simple_bind_s(LDAP_LOGIN, LDAP_PASSWORD)

myfilter = "memberOf=CN=nn-aws-aurora-users,OU=Groups,OU=test,DC=test,DC=com"
attrs = ['sAMAccountName', 'givenname', 'sn', 'mail', 'description', 'telephonenumber', 'homephone', 'mobile']
ldap_result = connect.search_s(BASE_DN, ldap.SCOPE_SUBTREE, myfilter, attrs)

Solution

  • As far as I see, the result is a tuple and the tuple's second element is a dict. So firstly you should get the second element of the tuple with ldap_result[1] and then you should access to the givenName field of dict.

    So if you combine all of these:

    ldap_result[1]["givenName"] will return the list of users.