Getting a listing of the user groups from Active Directory (AD) is very similar to getting the list of users. We are making use of the ldap3 module. Giovanni Cannata provided us a pretty sweet tool. Send the brother some love.

The key difference between the User listing and the Group listing is the query specification. In the code below we have changed the query from '(objectclass=person)' to '(objectclass=group)'. The other changes from the user listing to this group listing are formatting changes to print the results in a stunningly beautiful layout. Sort of. 🙂


import sys
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError

server_name = ‘your_server’
domain_name = ‘your_domain’
user_name = ‘your_username’
password = ‘your_password’

format_string = ‘{:40} {}’
print(format_string.format(‘Group’, ‘Description’))

server = Server(server_name, get_info=ALL)
conn = Connection(server, user='{}\\{}’.format(domain_name, user_name), password=password, authentication=NTLM,
auto_bind=True)
conn.search(‘dc={},dc=local’.format(domain_name), ‘(objectclass=group)’,
attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])

for e in sorted(conn.entries):
try:
desc = e.description
except LDAPCursorError:
desc = “”
print(format_string.format(str(e.name), desc))

Here’s the full source code for you to grab:
list_groups source code.

Under what circumstances have you had to search for users in groups?

Share This