1

I am trying to query Active directory through LDAP to list groups but I get more information than I need. How can I parse the result to only get all group names. For example: LOCAL_java_read and the others and not the rest from the result.

from ldap3 import Server, Connection, ALL
server = Server('xxx', port=389, get_info=ALL)
conn = Connection(server, 'username', 'password', auto_bind=True, raise_exceptions=True)
conn.search('OU=Groups,OU=CH,DC=google,DC=com', '(objectclass=group)')
groups=conn.entries
print (groups)

Result:

[DN: CN=LOCAL_java_read,OU=Groups,OU=CH,DC=google,DC=com - STATUS: Read - READ TIME: 2019-03-27T14:22:08.072330
, DN: CN=LOCAL_python_read,OU=Groups,OU=CH,DC=google,DC=com - STATUS: Read - READ TIME: 2019-03-27T14:22:08.072330
, DN: CN=LOCAL_php_read,OU=Groups,OU=CH,DC=google,DC=com - STATUS: Read - READ TIME: 2019-03-27T14:22:08.072330]

2 Answers2

0

I am not sure how Active directory structures its attributes but I believe you can just use a wildcard * to get the groups by changing the search.

conn.search('OU=Groups,OU=CH,DC=google,DC=com', '(&(objectClass=group)(CN=*))')

Microsoft's site has information about LDAP search filters which are most likely relevant to AD. There are some examples about Wildcards

Nathan McCoy
  • 3,092
  • 1
  • 24
  • 46
  • why not just try `CN=*` without the `objectClass`. regardless, search filters will work. you just need to make the right one. – Nathan McCoy Mar 27 '19 at 14:08
  • Hmm, that did not work either. So looking for a solution here. –  Mar 27 '19 at 14:36
  • sorry, cant be more help without a real AD environment. There are command line tools you can test until you have what you are looking for such as `ldapsearch` – Nathan McCoy Mar 27 '19 at 14:46
0

You could extract group names from the individual group entries using regex:

import re
stripped_groups = [re.sub(r'^.+? CN=([^,\s]+),?.*$', r'\1', str(entry)) for entry in groups]
print(stripped_groups)

Although I assume a @Nathan McCoy's answer might ultimately lead to a cleaner and better solution.

fabianegli
  • 2,056
  • 1
  • 18
  • 35
  • I agree. However the ldap search/filtering does not seem to work. So this could also be a good try. –  Mar 27 '19 at 17:41
  • I get this when I ran it: `expected string or bytes-like object` –  Mar 28 '19 at 07:16
  • so this means the strings in the list are bytestrings and we have to convert them before using with regex. I adapted my answer to reflect that. – fabianegli Mar 28 '19 at 10:40
  • Instead of `str(entry)`, you could also use `entry.decode()`. In any case it might be worth checking out https://docs.python.org/3/library/stdtypes.html#str or https://docs.python.org/3/reference/lexical_analysis.html#strings – fabianegli Mar 28 '19 at 10:55