Apologies in advance if this question has already been asked, have done some searching but no luck.
TL;DR: Trying to pull second piece of a tuple out as a string.
I am building a script with python3 that pulls information from LDAP and returns what is hopefully actionable data.
def GetMembersWDept():
i2 = input('Please input the department number. Examples: 2410, 2417\n')
criteria = '(&(objectClass=User)(department=' + i2 + '*))'
print ('Search criteria set to: \t\t' + criteria)
searchDC = 'dc=example,dc=com'
print ('Searching location: \t\t\t' + searchDC)
print ()
out = []
result = c.search(searchDC, criteria, \
SEARCH_SCOPE_WHOLE_SUBTREE, attributes = ['department']) \
# request a few object from the ldap server
if result:
for r in c.response:
if (r['type'] == 'searchResEntry'):
out.append(r['dn'])
out.append(r['attributes']) # comes out in tuple form
else:
pass
else:
print('result', conn.result)
return out
This works well for pulling out the CN of the members in that department but not for extracting whatever additional information, in this case the department, is appended.
A sample output is:
Search criteria set to: (&(objectClass=User)(department=2417*)) Searching location: dc=ple,dc=com
['CN=First Last,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}, 'CN=Another Person,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}]
How can I pull out the second portion of the tuple, ie '1234', as a string instead? The endgame here would be to format the data as:
[First Last, 1234, Another Person, 1234]
... so I can use it in another function that compares the department and returns the name if conditions are not met.
If output is:
['CN=First Last,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}, 'CN=Another Person,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}]
then you can set that equal to newresult
and do:
print(list(newresult[1].values())[0][0])
This assumes that the element in the list with the department is always in position 1, that the dictionary always has 1 value to it, and that the department number you want is the only item in the list.
IMHO, it would be simpler to use c.search_s
instead of c.search
, unless you have good reasons to do so (or you should show how you are creating your response).
From python-ldap documentation : search_s
directly returns a list of 2-tuple (dn, attrs), where dn is a string containing the DN (distinguished name) of the entry, and attrs is a dictionary containing the attributes associated with the entry. The keys of attrs are strings, and the associated values are lists of strings
So for each tuple entry
you have :
dn = entry[0]
departement = entry[1]{'department'}[0]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.