Python ldap.SCOPE_BASE Examples

The following are 25 code examples of ldap.SCOPE_BASE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ldap , or try the search function .
Example #1
Source File: ldap_attr.py    From isam-ansible-roles with Apache License 2.0 6 votes vote down vote up
def exact(self):
        try:
            results = self.connection.search_s(
                self.dn, ldap.SCOPE_BASE, attrlist=[self.name])
        except ldap.LDAPError:
            e = get_exception()
            self.module.fail_json(
                msg="Cannot search for attribute %s" % self.name,
                details=str(e))

        current = results[0][1].get(self.name, [])
        modlist = []

        if frozenset(self.values) != frozenset(current):
            if len(current) == 0:
                modlist = [(ldap.MOD_ADD, self.name, self.values)]
            elif len(self.values) == 0:
                modlist = [(ldap.MOD_DELETE, self.name, None)]
            else:
                modlist = [(ldap.MOD_REPLACE, self.name, self.values)]

        return modlist 
Example #2
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 6 votes vote down vote up
def _anon_bind(self):
        self._log.debug('Checking for anonymous bind...')
        results = self._search(
            'cn=config',
            '(objectClass=*)',
            ['nsslapd-allow-anonymous-access'],
            scope=ldap.SCOPE_BASE
        )
        dn, attrs = results[0]
        state = attrs['nsslapd-allow-anonymous-access'][0].decode('utf-8')

        if state in ['on', 'off', 'rootdse']:
            r = str(state).upper()
        else:
            r = 'ERROR'

        self._log.debug(r)
        return r 
Example #3
Source File: windapsearch.py    From windapsearch with GNU General Public License v3.0 6 votes vote down vote up
def getDefaultNamingContext(self):
        try:
            newCon = ldap.initialize('ldap://{}'.format(self.dc_ip))
            newCon.simple_bind_s('', '')
            res = newCon.search_s("", ldap.SCOPE_BASE, '(objectClass=*)')
            rootDSE = res[0][1]
        except ldap.LDAPError as e:
            print("[!] Error retrieving the root DSE")
            print("[!] {}".format(e))
            sys.exit(1)

        if 'defaultNamingContext' not in rootDSE:
            print("[!] No defaultNamingContext found!")
            sys.exit(1)

        defaultNamingContext = rootDSE['defaultNamingContext'][0].decode()

        self.domainBase = defaultNamingContext
        newCon.unbind()
        return defaultNamingContext 
Example #4
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 6 votes vote down vote up
def _count_users(self, user_base):
        self._log.debug('Counting %s users...' % user_base)
        results = self._search(
            getattr(self, '_%s_user_base' % user_base),
            '(objectClass=*)',
            ['numSubordinates'],
            scope=ldap.SCOPE_BASE
        )

        if not results and type(results) is not list:
            r = 0
        else:
            dn, attrs = results[0]
            r = attrs['numSubordinates'][0].decode('utf-8')

        self._log.debug(r)
        return r 
Example #5
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 6 votes vote down vote up
def _get_context(self):
        self._log.debug('Grabbing default context from LDAP')
        results = self._search(
            'cn=config',
            '(objectClass=*)',
            ['nsslapd-defaultnamingcontext'],
            scope=ldap.SCOPE_BASE
        )

        if not results and type(results) is not list:
            r = None
        else:
            dn, attrs = results[0]
            r = attrs['nsslapd-defaultnamingcontext'][0].decode('utf-8')

        self._log.debug(r)
        return r 
Example #6
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 6 votes vote down vote up
def _get_fqdn(self):
        self._log.debug('Grabbing FQDN from LDAP')
        results = self._search(
            'cn=config',
            '(objectClass=*)',
            ['nsslapd-localhost'],
            scope=ldap.SCOPE_BASE
        )

        if not results and type(results) is not list:
            r = None
        else:
            dn, attrs = results[0]
            r = attrs['nsslapd-localhost'][0].decode('utf-8')

        self._log.debug(r)
        return r 
Example #7
Source File: externalldap.py    From quay with Apache License 2.0 6 votes vote down vote up
def _ldap_user_search_with_rdn(self, conn, username_or_email, user_search_dn, suffix=""):
        query = "(|({0}={2}{3})({1}={2}{3}))".format(
            self._uid_attr, self._email_attr, escape_filter_chars(username_or_email), suffix
        )
        query = self._add_user_filter(query)

        logger.debug("Conducting user search: %s under %s", query, user_search_dn)
        try:
            return (conn.search_s(user_search_dn, ldap.SCOPE_SUBTREE, query), None)
        except ldap.REFERRAL as re:
            referral_dn = self._get_ldap_referral_dn(re)
            if not referral_dn:
                return (None, "Failed to follow referral when looking up username")

            try:
                subquery = "(%s=%s)" % (self._uid_attr, username_or_email)
                subquery = self._add_user_filter(subquery)
                return (conn.search_s(referral_dn, ldap.SCOPE_BASE, subquery), None)
            except ldap.LDAPError:
                logger.debug("LDAP referral search exception")
                return (None, "Username not found")

        except ldap.LDAPError:
            logger.debug("LDAP search exception")
            return (None, "Username not found") 
Example #8
Source File: ldapconn.py    From zabbix-ldap-sync with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_user_givenName(self, dn):
        """
        Retrieves the 'givenName' attribute of an LDAP user

        Args:
            username (str): The LDAP distinguished name to lookup

        Returns:
            The user's given name attribute

        """
        attrlist = ['givenName']

        result = self.conn.search_s(base=dn,
                                    scope=ldap.SCOPE_BASE,
                                    attrlist=attrlist)

        if not result:
            return None

        dn, data = result.pop()

        name = data.get('givenName')

        if not name:
            return None

        return name.pop() 
Example #9
Source File: backend.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _load_user_attrs(self):
        if self.dn is not None:
            search = LDAPSearch(
                self.dn, ldap.SCOPE_BASE, attrlist=self.settings.USER_ATTRLIST
            )
            results = search.execute(self.connection)

            if results is not None and len(results) > 0:
                self._user_attrs = results[0][1] 
Example #10
Source File: ldapconn.py    From zabbix-ldap-sync with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_user_sn(self, dn):
        """
        Retrieves the 'sn' attribute of an LDAP user

        Args:
            username (str): The LDAP distinguished name to lookup

        Returns:
            The user's surname attribute

        """
        attrlist = ['sn']

        result = self.conn.search_s(base=dn,
                                    scope=ldap.SCOPE_BASE,
                                    attrlist=attrlist)

        if not result:
            return None

        dn, data = result.pop()

        sn = data.get('sn')

        if not sn:
            return None

        return sn.pop() 
Example #11
Source File: ldapconn.py    From zabbix-ldap-sync with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_user_media(self, dn, ldap_media):
        """
        Retrieves the 'media' attribute of an LDAP user

        Args:
            username (str): The LDAP distinguished name to lookup
            ldap_media (str): The name of the field containing the media address

        Returns:
            The user's media attribute value

        """
        attrlist = [ldap_media]

        result = self.conn.search_s(base=dn,
                                    scope=ldap.SCOPE_BASE,
                                    attrlist=attrlist)

        if not result:
            return None

        dn, data = result.pop()

        mail = data.get(ldap_media)

        if not mail:
            return None

        return mail.pop() 
Example #12
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 5 votes vote down vote up
def _count_hostgroups(self):
        self._log.debug('Counting host groups...')
        results = self._search(
            'cn=hostgroups,cn=accounts,%s' % self._base_dn,
            '(objectClass=*)',
            ['numSubordinates'],
            scope=ldap.SCOPE_BASE
        )
        dn, attrs = results[0]
        r = attrs['numSubordinates'][0].decode('utf-8')
        self._log.debug(r)
        return r 
Example #13
Source File: client_libldap.py    From code with MIT License 5 votes vote down vote up
def search(self, base, filter=None, scope=None, attrs=None):
        scope = {
            "base":         ldap.SCOPE_BASE,
            "subtree":      ldap.SCOPE_SUBTREE,
            "sub":          ldap.SCOPE_SUBTREE,
            "onelevel":     ldap.SCOPE_ONELEVEL,
            "one":          ldap.SCOPE_ONELEVEL,
            "subordinate":  ldap.SCOPE_SUBORDINATE,
            "child":        ldap.SCOPE_SUBORDINATE,
        }[scope or "subtree"]
        result = self.conn.search_ext_s(base, scope, filter, attrs)
        result = [(dn, CaseInsensitiveDict(attrs)) for (dn, attrs) in result]
        return result 
Example #14
Source File: plugin.py    From allura with Apache License 2.0 5 votes vote down vote up
def _get_pref(self, username, pref_name):
        con = ldap_conn()
        try:
            rs = con.search_s(ldap_user_dn(username), ldap.SCOPE_BASE)
        except ldap.NO_SUCH_OBJECT:
            rs = []
        else:
            con.unbind_s()
        if not rs:
            log.warning('LdapUserPref: No user record found for: {}'.format(username))
            return ''
        user_dn, user_attrs = rs[0]
        ldap_attr = self.fields[pref_name]
        # assume single-valued list
        return user_attrs[ldap_attr][0].decode('utf-8') 
Example #15
Source File: sync_ldap_groups_to_svn_authz.py    From sync-ldap-groups-to-svn-authz with MIT License 5 votes vote down vote up
def get_groups(ldapobject):
  """This function will search the LDAP directory for the specificied group DNs."""

  groups = []
  for group_dn in group_dns:
    try:
      result_set = get_ldap_search_resultset(group_dn, group_query, ldapobject, ldap.SCOPE_BASE)
      for i in range(len(result_set)):
        for entry in result_set[i]:
          groups.append(entry)
    except ldap.NO_SUCH_OBJECT, e:
      if not silent:
        sys.stderr.write("Couldn't find a group with DN %s.\n" % group_dn)
      raise e 
Example #16
Source File: __init__.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get_user_info(self, username):
        conn = self._get_ldap_conn()
        conn.simple_bind_s(self.instance.config.get("bind_dn"), self.instance.config.get("bind_password"))
        user_dn = self._get_user_dn(username)
        results = conn.search_s(user_dn, ldap.SCOPE_BASE, attrlist=["*"])
        return cleanup_value(results[0][1]) 
Example #17
Source File: config.py    From ssh-ldap-pubkey with MIT License 5 votes vote down vote up
def parse_scope_opt(value):
    """Convert `scope` option to ldap's `SCOPE_*` constant."""
    return {
        'base': ldap.SCOPE_BASE,
        'one': ldap.SCOPE_ONELEVEL,
        'sub': ldap.SCOPE_SUBTREE
    }[value.lower()] if value else None 
Example #18
Source File: __init__.py    From ssh-ldap-pubkey with MIT License 5 votes vote down vote up
def _find_pubkeys(self, dn):
        conf = self.conf
        result = self._conn.search_s(
            dn, ldap.SCOPE_BASE, attrlist=[conf.pubkey_attr])

        return map(_decode, result[0][1].get(conf.pubkey_attr, [])) 
Example #19
Source File: windapsearch.py    From windapsearch with GNU General Public License v3.0 5 votes vote down vote up
def getFunctionalityLevel(self):
        objectFilter = '(objectclass=*)'
        attrs = ['domainFunctionality', 'forestFunctionality', 'domainControllerFunctionality']
        try:
            # rawFunctionality = self.do_ldap_query('', ldap.SCOPE_BASE, objectFilter, attrs)
            rawData = self.con.search_s('', ldap.SCOPE_BASE, "(objectclass=*)", attrs)
            functionalityLevels = rawData[0][1]
        except Error as e:
            print("[!] Error retrieving functionality level")
            print("[!] {}".format(e))
            sys.exit(1)

        return functionalityLevels 
Example #20
Source File: windapsearch_py2.py    From windapsearch with GNU General Public License v3.0 5 votes vote down vote up
def getFunctionalityLevel(self):
		objectFilter = '(objectclass=*)'
		attrs = ['domainFunctionality', 'forestFunctionality', 'domainControllerFunctionality']
		try:
			# rawFunctionality = self.do_ldap_query('', ldap.SCOPE_BASE, objectFilter, attrs)
			rawData = self.con.search_s('', ldap.SCOPE_BASE, "(objectclass=*)", attrs)
			functionalityLevels = rawData[0][1]
		except Error, e:
			print "[!] Error retrieving functionality level"
			print "[!] {}".format(e)
			sys.exit(1) 
Example #21
Source File: windapsearch_py2.py    From windapsearch with GNU General Public License v3.0 5 votes vote down vote up
def getDefaultNamingContext(self):
		try:
			newCon = ldap.initialize('ldap://{}'.format(self.dc_ip))
			newCon.simple_bind_s('','')
			res = newCon.search_s("", ldap.SCOPE_BASE, '(objectClass=*)')
			rootDSE = res[0][1]
		except ldap.LDAPError, e:
			print "[!] Error retrieving the root DSE"
			print "[!] {}".format(e)
			sys.exit(1) 
Example #22
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_profile(self, uid, password):
        c = self.connect()
        ldap_result = c.search_s(self.get_user_dn(uid), ldap.SCOPE_BASE)[0][1]
        profile = {}
        profile['uid'] = ldap_result['uid'][0]
        profile['name'] = ldap_result['displayName'][0].decode('utf-8')
        profile['email'] = ldap_result['mail'][0]
        profile['picture'] = ldap_result['jpegPhoto'][0] if ('jpegPhoto' in ldap_result and
                                                             ldap_result['jpegPhoto']) else None
        c.unbind()
        return profile 
Example #23
Source File: ldap_backend.py    From st2-auth-backend-ldap with Apache License 2.0 5 votes vote down vote up
def _scope_to_ldap_option(self, scope):
        """
        Transform scope string into ldap module constant.
        """
        if 'base' in scope.lower():
            opt = ldap.SCOPE_BASE
        elif 'onelevel' in scope.lower():
            opt = ldap.SCOPE_ONELEVEL
        else:
            opt = ldap.SCOPE_SUBTREE
        return opt 
Example #24
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_populate_with_attrlist(self, mock):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            USER_ATTR_MAP={"first_name": "givenName", "last_name": "sn"},
            USER_ATTRLIST=["*", "+"],
        )

        user = authenticate(username="alice", password="password")

        self.assertEqual(user.username, "alice")

        # lookup user attrs
        mock.assert_called_once_with(
            "uid=alice,ou=people,o=test", ldap.SCOPE_BASE, "(objectClass=*)", ["*", "+"]
        ) 
Example #25
Source File: users.py    From core with GNU General Public License v3.0 4 votes vote down vote up
def add(self, passwd):
        """
        Add the user to LDAP.

        :param str passwd: user password to set
        """
        try:
            ldif = conns.LDAP.search_s(
                self.ldap_id, ldap.SCOPE_BASE, "(objectClass=*)", None)
            msg = "A user named {0} already exists".format(self.name)
            raise errors.InvalidConfigError(msg)
        except ldap.NO_SUCH_OBJECT:
            pass

        # Create LDAP user with proper metadata
        ldif = {
            "objectClass": [b"mailAccount", b"inetOrgPerson", b"posixAccount"],
            "givenName": [b(self.first_name)],
            "sn": [b(self.last_name)] if self.last_name else [b"NONE"],
            "displayName": [b(self.full_name)],
            "cn": [b(self.full_name)],
            "uid": [b(self.name)],
            "mail": [b(self.name + "@" + self.domain)],
            "maildrop": [b(self.name)],
            "userPassword": [b(ldap_sha512_crypt.encrypt(passwd))],
            "gidNumber": [b"100"],
            "uidNumber": [b(str(self.uid))],
            "homeDirectory": [b("/home/" + self.name)],
            "loginShell": [b"/usr/bin/bash"]
            }
        ldif = ldap.modlist.addModlist(ldif)
        signals.emit("users", "pre_add", self)
        logger.debug("Roles", "Adding user: {0}".format(self.ldap_id))
        conns.LDAP.add_s(self.ldap_id, ldif)
        modes = ["admin" if self.admin else "", "sudo" if self.sudo else ""]
        msg = "Setting user modes: {0}".format(", ".join(modes))
        logger.debug("Roles", msg)

        self.update_adminsudo()
        self.update_samba(passwd)

        signals.emit("users", "post_add", {"user": self, "passwd": passwd})