Search code examples
pythonif-statementactive-directoryldap3

Check if current user is in a specific group if so execute some code else quit


I am pretty new to python and active directory. I used a little bit of ldap3 to search the AD for the members of the group.

  1. Can I somehow check if the current user is in a specific AD group and if that is the case some more code executes?

  2. Is there a better way to get the distinguishedName, server connection etc.?

  3. Also i would like to not use any passwords or login information since i just dont want it to be in the code if that is even possible

The main problem for me is currently that i dont know and dont understand how to check for membership or if thats even possible

This is the Code i have now:

from ldap3 import Server, Connection, ALL
import ctypes

pw = '*********'

print()


def get_data(extended_name_format: int):
    get_user_name_ex = ctypes.windll.secur32.GetUserNameExW
    data = extended_name_format

    size = ctypes.pointer(ctypes.c_ulong(0))
    get_user_name_ex(data, None, size)

    name_buffer = ctypes.create_unicode_buffer(size.contents.value)
    get_user_name_ex(data, name_buffer, size)
    return name_buffer.value


displayName = get_data(3)
distinguishedName = get_data(1)
print(displayName)
print(distinguishedName)
print()

server = Server('**dom1.***.***', get_info=ALL)
conn = Connection(server, auto_bind=True)
print(conn)

entries = conn.extend.standard.paged_search('CN=***,OU=***,OU=***,OU=***,DC=***,DC=***', '(member=*)', attributes=['member'], paged_size=5)
for entry in entries:
    print(entry)

if distinguishedName == entries:
    print('yay')
else:
    print('nope')

Solution

  • The member attribute of a group contains the "distinguished name" of each member. That is a format that looks like CN=SomeUser,OU=Users,DC=example,DC=com.

    You're already using GetUserNameExW to get the username. You can use that to get the distinguished name by passing a value of 1 for the NameFormat parameter, which corresponds to NameFullyQualifiedDN.