当前位置: 首页>>代码示例>>Python>>正文


Python ldap3.SIMPLE属性代码示例

本文整理汇总了Python中ldap3.SIMPLE属性的典型用法代码示例。如果您正苦于以下问题:Python ldap3.SIMPLE属性的具体用法?Python ldap3.SIMPLE怎么用?Python ldap3.SIMPLE使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在ldap3的用法示例。


在下文中一共展示了ldap3.SIMPLE属性的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: connect

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def connect(self):
        # check configuration
        if not (hasattr(settings, 'LDAP_SERVERS') and hasattr(settings, 'LDAP_BIND_ADMIN') and
                hasattr(settings, 'LDAP_BIND_ADMIN_PASS') and hasattr(settings, 'LDAP_AD_DOMAIN')
                and hasattr(settings, 'LDAP_CERT_FILE')
                ):
            raise ImproperlyConfigured()

        # first: build server pool from settings
        tls = Tls(validate=ssl.CERT_OPTIONAL, version=ssl.PROTOCOL_TLSv1, ca_certs_file=settings.LDAP_CERT_FILE)

        if self.pool is None:
            self.pool = ServerPool(None, pool_strategy=FIRST, active=True)
            for srv in settings.LDAP_SERVERS:
                # Only add servers that supports SSL, impossible to make changes without
                if srv['use_ssl']:
                    server = Server(srv['host'], srv['port'], srv['use_ssl'], tls=tls)
                    self.pool.add(server)

        # then, try to connect with user/pass from settings
        self.con = Connection(self.pool, auto_bind=True, authentication=SIMPLE,
                              user=settings.LDAP_BIND_ADMIN, password=settings.LDAP_BIND_ADMIN_PASS) 
开发者ID:Lucterios2,项目名称:django_auth_ldap3_ad,代码行数:24,代码来源:ad_users.py

示例2: check

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def check(self, dn=None, passwd=None):
        """:func:`burpui.misc.auth.ldap.LdapLoader.check` authenticates a user
        against the LDAP server.

        :param dn: canonical `dn` of the user to authenticate as
        :type dn: str

        :param passwd: password of the user to authenticate as
        :type passwd: str

        :returns: True if bind was successful, otherwise False
        """
        try:
            with Connection(self.server, user='{0}'.format(dn), password=passwd, raise_exceptions=True, auto_bind=self.auto_bind, authentication=SIMPLE) as con:
                self.logger.debug('LDAP Connection = {0}'.format(str(con)))
                self.logger.info('Bound as user: {0}'.format(dn))
                return con.bind()
        except Exception as e:
            self.logger.error('Failed to authenticate user: {0}, {1}'.format(dn, str(e)))

        self.logger.error('Bind as \'{0}\' failed'.format(dn))
        return False 
开发者ID:ziirish,项目名称:burp-ui,代码行数:24,代码来源:ldap.py

示例3: ldap_query

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def ldap_query(self, query):

        if not self.ldap_enabled:
            return None

        from ldap3 import Server, Connection, SIMPLE, SYNC, ASYNC, SUBTREE, ALL, ALL_ATTRIBUTES
        import json

        try:
            logging.debug("connecting to ldap server {} on port {}".format(self.ldap_server, self.ldap_port))
            with Connection(
                Server(self.ldap_server, port = self.ldap_port, get_info = ALL), 
                auto_bind = True,
                client_strategy = SYNC,
                user=self.ldap_bind_user,
                password=self.ldap_bind_password,
                authentication=SIMPLE, 
                check_names=True) as c:

                logging.debug("running ldap query for ({})".format(query))
                c.search(self.ldap_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 ldap query {}: {}".format(query, e))
            return None 
开发者ID:IntegralDefense,项目名称:ACE,代码行数:37,代码来源:__init__.py

示例4: tivoli_ldap_query

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def tivoli_ldap_query(self, query):                                                                                        
        
        if not self.tivoli_ldap_enabled:                                                                                       
            return None
                                                                                                 
        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 
开发者ID:IntegralDefense,项目名称:ACE,代码行数:37,代码来源:__init__.py

示例5: setUp

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def setUp(self):
        ldap3mock.setLDAPDirectory(LDAPDirectory)

        host = "localhost"
        u = "manager"
        p = "ldaptest"
        self.base = "o=test"

        srv = ldap3.Server(host, port=389, use_ssl=False, connect_timeout=5)
        self.c = ldap3.Connection(srv, user=u, password=p,
                                  auto_referrals=False,
                                  client_strategy=ldap3.SYNC, check_names=True,
                                  authentication=ldap3.SIMPLE, auto_bind=False)
        self.c.open()
        self.c.bind() 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:17,代码来源:test_mock_ldap3.py

示例6: ldap_authenticate

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def ldap_authenticate(request,username,password,groups_allowed=True):
  #change these values to what is appropriate for your environment
  id_name="uid"
  ldap_host="192.168.0.2"
  ldap_port="389"
  bind_dn="cn=Manager,dc=bbotte,dc=com"
  bind_pass="123456"
  user_base="ou=People,dc=bbotte,dc=com"
  
  #bind with service account
  s = Server(ldap_host, port=int(ldap_port), get_info=ALL)
  c = Connection(
    s,
    authentication=SIMPLE, 
    user=bind_dn,
    password=bind_pass,
    check_names=True, 
    lazy=False, 
    client_strategy=SYNC, 
    raise_exceptions=False)
  c.open()
  c.bind()
  if c.bound:
    #once bound, check username provided and get cn, memberOf list and mail
    # get cn_name
    c.search(user_base,'(%s=%s)'%(id_name,username),attributes=['cn','mail'])
    c.unbind
    try: 
      cn_name=c.entries[0].cn
    except:
      print("user cn cannot be found")
      auth_logger.error("user cn cannot be found")
      
    session['username']=username
    return True
  else:
    auth_logger.debug('ldap bind failed')
    c.unbind()
    return False 
开发者ID:bbotte,项目名称:bbotte.github.io,代码行数:41,代码来源:auth_ldap3.py

示例7: change_password_ldap

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def change_password_ldap(conf, username, old_pass, new_pass):
    with connect_ldap(conf) as c:
        user_dn = find_user_dn(conf, c, username)

    # Note: raises LDAPUserNameIsMandatoryError when user_dn is None.
    with connect_ldap(conf, authentication=SIMPLE, user=user_dn, password=old_pass) as c:
        c.bind()
        c.extend.standard.modify_password(user_dn, old_pass, new_pass) 
开发者ID:jirutka,项目名称:ldap-passwd-webui,代码行数:10,代码来源:app.py

示例8: change_password_ad

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def change_password_ad(conf, username, old_pass, new_pass):
    user = username + '@' + conf['ad_domain']

    with connect_ldap(conf, authentication=SIMPLE, user=user, password=old_pass) as c:
        c.bind()
        user_dn = find_user_dn(conf, c, username)
        c.extend.microsoft.modify_password(user_dn, new_pass, old_pass) 
开发者ID:jirutka,项目名称:ldap-passwd-webui,代码行数:9,代码来源:app.py

示例9: parse_config

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def parse_config(config):
        class _LdapConfig(object):
            pass

        ldap_config = _LdapConfig()

        ldap_config.enabled = config.get("enabled", False)

        ldap_config.mode = LDAPMode.SIMPLE

        # verify config sanity
        _require_keys(config, [
            "uri",
            "base",
            "attributes",
        ])

        ldap_config.uri = config["uri"]
        ldap_config.start_tls = config.get("start_tls", False)
        ldap_config.base = config["base"]
        ldap_config.attributes = config["attributes"]

        if "bind_dn" in config:
            ldap_config.mode = LDAPMode.SEARCH
            _require_keys(config, [
                "bind_dn",
                "bind_password",
            ])

            ldap_config.bind_dn = config["bind_dn"]
            ldap_config.bind_password = config["bind_password"]
            ldap_config.filter = config.get("filter", None)

        # verify attribute lookup
        _require_keys(config['attributes'], [
            "uid",
            "name",
            "mail",
        ])

        return ldap_config 
开发者ID:matrix-org,项目名称:matrix-synapse-ldap3,代码行数:43,代码来源:ldap_auth_provider.py

示例10: login

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def login(username: str, password: str) -> tuple:

    try:
        if SERVER.lower().startswith("ldaps://"):
            server = Server(SERVER, port = PORT, get_info = NONE, use_ssl = True) 
        else:
            server = Server(SERVER, port = PORT, get_info = NONE, use_ssl = False)  # define an unsecure LDAP server, requesting info on DSE and schema

        c = None

        if BIND_DN is not None and BIND_DN != '':
            c = Connection(server, auto_bind = True, client_strategy = SYNC, user=BIND_DN, password=BIND_PASSWORD, authentication=SIMPLE, check_names=True)
        else:
            c = Connection(server, auto_bind = True, client_strategy = SYNC, user=None, password=None, authentication=ANONYMOUS, check_names=True)

    except Exception as e:
        error = "Error connecting to LDAP server: %s" % e
        raise LDAPLoginError({"error_message": error})

    try:
        if(SEARCH_SUFFIX is not None and SEARCH_SUFFIX != ''):
            search_filter = '(%s=%s)' % (SEARCH_PROPERTY, username + SEARCH_SUFFIX)
        else:
            search_filter = '(%s=%s)' % (SEARCH_PROPERTY, username)
        if SEARCH_FILTER:
            search_filter = '(&%s(%s))' % (search_filter, SEARCH_FILTER)
        c.search(search_base = SEARCH_BASE,
                 search_filter = search_filter,
                 search_scope = SUBTREE,
                 attributes = [EMAIL_PROPERTY,FULL_NAME_PROPERTY],
                 paged_size = 5)

        if len(c.response) > 0:
            dn = c.response[0].get('dn')
            user_email = c.response[0].get('raw_attributes').get(EMAIL_PROPERTY)[0].decode('utf-8')
            full_name = c.response[0].get('raw_attributes').get(FULL_NAME_PROPERTY)[0].decode('utf-8')

            user_conn = Connection(server, auto_bind = True, client_strategy = SYNC, user = dn, password = password, authentication = SIMPLE, check_names = True)

            return (user_email, full_name)

        raise LDAPLoginError({"error_message": "Username or password incorrect"})

    except Exception as e:
        error = "LDAP account or password incorrect: %s" % e
        raise LDAPLoginError({"error_message": error}) 
开发者ID:ensky,项目名称:taiga-contrib-ldap-auth,代码行数:48,代码来源:connector.py

示例11: bind_ldap_user

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def bind_ldap_user(self, username, password):
        """
        Attempts to bind the specified username and password and returns
        an LDAPUser object representing the user.

        Returns None if the bind was unsuccessful.

        This implements direct binding.
        """

        # Construct the user to bind as
        if settings.BIND_TEMPLATE:
            # Full CN
            ldap_bind_user = settings.BIND_TEMPLATE.format(username=username,
                    base_dn=settings.BASE_DN)
        elif settings.USERNAME_PREFIX:
            # Prepend a prefix: useful for DOMAIN\user
            ldap_bind_user = settings.USERNAME_PREFIX + username
        elif settings.USERNAME_SUFFIX:
            # Append a suffix: useful for user@domain
            ldap_bind_user = username + settings.USERNAME_SUFFIX
        logger.debug('Attempting to authenticate to LDAP by binding as ' + ldap_bind_user)

        try:
            c = ldap3.Connection(self.backend,
                    read_only=True,
                    lazy=False,
                    auto_bind=True,
                    client_strategy=ldap3.SYNC,
                    authentication=ldap3.SIMPLE,
                    user=ldap_bind_user,
                    password=password)
        except ldap3.core.exceptions.LDAPSocketOpenError as e:
            logger.error('LDAP connection error: ' + str(e))
            return None
        except ldap3.core.exceptions.LDAPBindError as e:
            if 'invalidCredentials' in str(e):
                # Invalid bind DN or password
                return None
            else:
                logger.error('LDAP bind error: ' + str(e))
                return None
        except Exception as e:
            logger.exception('Caught exception when trying to connect and bind to LDAP')
            raise

        # Search for the user using their full DN
        search_filter = '({}={})'.format(settings.UID_ATTRIB, username)
        attributes = self.search_ldap(c, search_filter, attributes=LDAPUser._attrib_keys, size_limit=1)
        if not attributes:
            logger.error('LDAP search error: no results for ' + search_filter)
            return None

        # Construct an LDAPUser instance for this user
        return LDAPUser(c, attributes) 
开发者ID:sjkingo,项目名称:django_auth_ldap3,代码行数:57,代码来源:backends.py

示例12: _perform_custom_queries

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SIMPLE [as 别名]
def _perform_custom_queries(self, conn, custom_queries, tags, instance):
        """
        Perform custom queries to collect additional metrics like number of result and duration of the query
        """
        for query in custom_queries:
            name = query.get("name")
            if name is None:
                self.log.error("`name` field is required for custom query")
                continue
            search_base = query.get("search_base")
            if search_base is None:
                self.log.error("`search_base` field is required for custom query #%s", name)
                continue
            search_filter = query.get("search_filter")
            if search_filter is None:
                self.log.error("`search_filter` field is required for custom query #%s", name)
                continue
            attrs = query.get("attributes")
            if "username" in query:
                username = query.get("username")
                password = query.get("password")
                if not username:
                    # username is an empty string, we want anonymous bind
                    username = None
                    password = None
            else:
                # username not specified, we want to reuse the credentials for the monitor backend
                username = instance.get("username")
                password = instance.get("password")

            try:
                # Rebind with different credentials
                auth_method = ldap3.SIMPLE if username else ldap3.ANONYMOUS
                if username is None:
                    conn.user = None
                res = conn.rebind(user=username, password=password, authentication=auth_method)
                if not res:
                    raise ldap3.core.exceptions.LDAPBindError("Error binding to server: {}".format(conn.result))
            except ldap3.core.exceptions.LDAPBindError:
                self.log.exception("Could not rebind to server at %s to perform query %s", instance.get("url"), name)
                continue

            try:
                # Perform the search query
                conn.search(search_base, search_filter, attributes=attrs)
            except ldap3.core.exceptions.LDAPException:
                self.log.exception("Unable to perform search query for %s", name)
                continue

            query_tags = ['query:{}'.format(name)]
            query_tags.extend(tags)
            query_time = self._get_query_time(conn)
            results = len(conn.entries)
            self.gauge("{}.query.duration".format(self.METRIC_PREFIX), query_time, tags=query_tags)
            self.gauge("{}.query.entries".format(self.METRIC_PREFIX), results, tags=query_tags) 
开发者ID:DataDog,项目名称:integrations-core,代码行数:57,代码来源:openldap.py


注:本文中的ldap3.SIMPLE属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。