anonymously132526
anonymously132526

Reputation: 177

Is it possible to do ldap query and exclude certain OU?

Using python-ldap to search active directory. How do I exclude certain user with a specific OU? Searching within the group 'GON' and want it to return just regular users with OU=Users and not OU=Foo.

filter = "(&(CN=GON)(!(OU=Foo)))"
attr = ["member"]
scope = ldap.SCOPE_SUBTREE

result = l.search_s(basdn, scope, filter, attr)

Got result:

[('CN=GON,OU=App,OU=Groups,DC=com', {'member': [b'CN=user1,OU=Users,DC=com', b'CN=user2me,OU=Foo,DC=com',]}), (None, ['ldap://skogen.com/CN=Sche,CN=Conf,DC=com']), (None, ['ldap://skogen.com/CN=Sche,CN=Conf,DC=com'])]

Want result:

[('CN=GON,OU=App,OU=Groups,DC=com', {'member': [b'CN=user1,OU=Users,DC=com']}), (None, ['ldap://skogen.com/CN=Sche,CN=Conf,DC=com']), (None, ['ldap://skogen.com/CN=Sche,CN=Conf,DC=com'])]

Upvotes: 0

Views: 1927

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40858

The short answer is no.

The query filter only affects the objects returned, not the values of the attributes returned for that object. So the filter of (CN=GON) means, "I want to find a group with the cn is GON" and the attr value tells it which attributes to return. LDAP does not provide a way to modify how those attributes are returned.

You can filter them after the search is complete. Loop through each value and remove the ones you don't want.

Another way to find all users in one specific OU who are a member of a group is to look at the memberOf attribute. This will work in Active Directory, but I'm not sure about OpenLDAP (I think memberOf has to be configured to work, but I'm not sure - I've never actually used OpenLDAP).

So in AD, you can make a query like this:

basedn = "OU=Users,DC=com"
filter = "(&(objectClass=user)(objectCategory=person)(memberOf=CN=GON,OU=App,OU=Groups,DC=com))"
attr = ["distinguishedName"]
scope = ldap.SCOPE_SUBTREE

result = l.search_s(basdn, scope, filter, attr)

This works well in AD domains where there is only one domain in the forest. But in multi-domain forests, beware of memberOf.

Upvotes: 1

Related Questions