How to use the ldap3.SUBTREE function in ldap3

To help you get started, we’ve selected a few ldap3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github afourmy / eNMS / eNMS / controller / administration.py View on Github external
name, password = kwargs["name"], kwargs["password"]
        if kwargs["authentication_method"] == "Local User":
            user = fetch("user", allow_none=True, name=name)
            return user if user and password == user.password else False
        elif kwargs["authentication_method"] == "LDAP Domain":
            with Connection(
                self.ldap_client,
                user=f"{self.config['ldap']['userdn']}\\{name}",
                password=password,
                auto_bind=True,
                authentication=NTLM,
            ) as connection:
                connection.search(
                    self.config["ldap"]["basedn"],
                    f"(&(objectClass=person)(samaccountname={name}))",
                    search_scope=SUBTREE,
                    get_operational_attributes=True,
                    attributes=["cn", "memberOf", "mail"],
                )
                json_response = loads(connection.response_to_json())["entries"][0]
                if json_response and any(
                    group in s
                    for group in self.config["ldap"]["admin_group"].split(",")
                    for s in json_response["attributes"]["memberOf"]
                ):
                    user = factory(
                        "user",
                        **{
                            "name": name,
                            "password": password,
                            "email": json_response["attributes"].get("mail", ""),
                            "permissions": ["Admin"],
github IntegralDefense / ACE / lib / saq / modules / __init__.py View on Github external
from ldap3 import Server, Connection, SIMPLE, SYNC, ASYNC, SUBTREE, ALL, ALL_ATTRIBUTES                         
        import json                                                                                                     
                                                                                                                        
        try:                                                                                                            
            logging.debug("connecting to tivoli ldap server {} on port {}".format(self.tivoli_server, self.tivoli_ldap_port))           
            with Connection(                                                                                            
                Server(self.tivoli_server, port = self.tivoli_ldap_port , get_info = ALL),                                        
                auto_bind = False,                                                                                       
                client_strategy = SYNC,                                                                                 
                user=self.tivoli_bind_user,                                                                               
                password=self.tivoli_bind_password,                                                                       
                authentication=SIMPLE,                                                                                  
                check_names=True) as c:                                                                                 

                logging.debug("running tivoli ldap query for ({})".format(query))                                             
                c.search(self.tivoli_base_dn, '({})'.format(query), SUBTREE, attributes = ALL_ATTRIBUTES)                

                # a little hack to move the result into json                                                            
                response = json.loads(c.response_to_json())                                                             
                result = c.result                                                                                       

                if len(response['entries']) < 1:                                                                        
                    return None                                                                                         
                                                                                                                        
                # XXX not sure about the 0 here, I guess only if we only looking for one thing at a time                
                return response['entries'][0]['attributes']                                                             

        except Exception as e:                                                                                          
            logging.warning("failed tivoli ldap query {}: {}".format(query, e))                                           
            return None
github cannatag / ldap3 / ldap3 / extend / standard / PagedSearch.py View on Github external
def paged_search_generator(connection,
                           search_base,
                           search_filter,
                           search_scope=SUBTREE,
                           dereference_aliases=DEREF_ALWAYS,
                           attributes=None,
                           size_limit=0,
                           time_limit=0,
                           types_only=False,
                           get_operational_attributes=False,
                           controls=None,
                           paged_size=100,
                           paged_criticality=False):
    if connection.check_names and search_base:
        search_base = safe_dn(search_base)

    responses = []
    cookie = True  # performs search at least one time
    while cookie:
        result = connection.search(search_base,
github adobe-apiplatform / user-sync.py / user_sync / sign_sync / synchronize.py View on Github external
def get_extra_ldap_attr(self, connector, name):
        directory_option = self.config_loader.get_directory_connector_options(connector.name)
        base_dn = directory_option['base_dn']
        self.connection.search(base_dn, "(CN={})".format(name), ldap3.SUBTREE)
        user_data = self.connection.entries
        temp_user_info = dict()

        if 'company' in user_data:
            temp_user_info['company'] = user_data['company'][0].decode("utf-8")
        if 'title' in user_data:
            temp_user_info['title'] = user_data['title'][0].decode("utf-8")

        return temp_user_info
github cannatag / ldap3 / ldap3 / core / connection.py View on Github external
def search(self,
               search_base,
               search_filter,
               search_scope=SUBTREE,
               dereference_aliases=DEREF_ALWAYS,
               attributes=None,
               size_limit=0,
               time_limit=0,
               types_only=False,
               get_operational_attributes=False,
               controls=None,
               paged_size=None,
               paged_criticality=False,
               paged_cookie=None,
               auto_escape=None):
        """
        Perform an ldap search:

        - If attributes is empty noRFC2696 with the specified size
        - If paged is 0 and cookie is present the search is abandoned on
github etianen / django-python3-ldap / django_python3_ldap / ldap.py View on Github external
def iter_users(self):
        """
        Returns an iterator of Django users that correspond to
        users in the LDAP database.
        """
        paged_entries = self._connection.extend.standard.paged_search(
            search_base=settings.LDAP_AUTH_SEARCH_BASE,
            search_filter=format_search_filter({}),
            search_scope=ldap3.SUBTREE,
            attributes=ldap3.ALL_ATTRIBUTES,
            get_operational_attributes=True,
            paged_size=30,
        )
        return filter(None, (
            self._get_or_create_user(entry)
            for entry
            in paged_entries
            if entry["type"] == "searchResEntry"
        ))
github GluuFederation / community-edition-setup / static / scripts / change_hostname / change_gluu_host.py View on Github external
def change_uma(self):
        print "Changing LDAP UMA Configurations"

        for ou, cattr in (
                    ('resources','oxResource'),
                    ('scopes', 'oxId'),
                    ):

            dn = "ou={},ou=uma,o={},o=gluu".format(ou, self.base_inum)

            self.conn.search(search_base=dn, search_filter='(objectClass=*)', search_scope=SUBTREE, attributes=[cattr])
            result = self.conn.response

            for r in result:
                for i in range(len( r['attributes'][cattr])):
                    changeAttr = False
                    if self.old_host in r['attributes'][cattr][i]:
                        r['attributes'][cattr][i] = r['attributes'][cattr][i].replace(self.old_host, self.new_host)
                        self.conn.modify(r['dn'], {cattr: [MODIFY_REPLACE, r['attributes'][cattr]]})
github georchestra / georchestra / migrations / 15.12 / populate_stats_roles.py View on Github external
# object class of ldap object contaning group definition
GROUP_OBJECT_CLASS = 'groupOfMembers'



reg = re.compile(r"^uid=([a-zA-Z0-9_.-]+),")

if BIND_WITH_CREDENTIALS:
    conn = Connection(LDAP_URI, LDAP_BINDDN, LDAP_PASSWD, auto_bind=True)
else:
    conn = Connection(LDAP_URI, auto_bind=True)

conn.search(search_base = GROUPS_DN,
            search_filter = '(objectClass=%s)' % GROUP_OBJECT_CLASS,
            search_scope = SUBTREE,
            attributes = ['cn', 'member'])

usersGroups = {}

# Browsing Groups 

for entry in conn.entries:
    #print("Group found : %s" % entry.cn)
    try:
        for user in entry.member.values:
            if user not in usersGroups:
                usersGroups[user] = [entry.cn.value]
            else:
                usersGroups[user].append(entry.cn.value)
            #print("\tUser found : %s" % user)
    except LDAPException:
github jupyterhub / ldapauthenticator / ldapauthenticator / ldapauthenticator.py View on Github external
self.log.debug(msg)
            if is_bound:
                break

        if not is_bound:
            msg = "Invalid password for user '{username}'"
            self.log.warning(msg.format(username=username))
            return None

        if self.search_filter:
            search_filter = self.search_filter.format(
                userattr=self.user_attribute, username=username
            )
            conn.search(
                search_base=self.user_search_base,
                search_scope=ldap3.SUBTREE,
                search_filter=search_filter,
                attributes=self.attributes,
            )
            n_users = len(conn.response)
            if n_users == 0:
                msg = "User with '{userattr}={username}' not found in directory"
                self.log.warning(
                    msg.format(userattr=self.user_attribute, username=username)
                )
                return None
            if n_users > 1:
                msg = (
                    "Duplicate users found! "
                    "{n_users} users found with '{userattr}={username}'"
                )
                self.log.warning(