Python ldap 模块,SERVER_DOWN 实例源码

我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用ldap.SERVER_DOWN

项目:drastic-web    作者:UMD-DRASTIC    | 项目源码 | 文件源码
def ldapAuthenticate(username, password):
    if settings.AUTH_LDAP_SERVER_URI is None:
        return False

    if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
        return False

    try:
        connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
        connection.protocol_version = ldap.VERSION3
        user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
        connection.simple_bind_s(user_dn, password)
        return True
    except ldap.INVALID_CREDENTIALS:
        return False
    except ldap.SERVER_DOWN:
        return False
项目:drastic-web    作者:UMD-DRASTIC    | 项目源码 | 文件源码
def ldapAuthenticate(username, password):
    if settings.AUTH_LDAP_SERVER_URI is None:
        return False

    if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
        return False

    try:
        connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
        connection.protocol_version = ldap.VERSION3
        user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
        connection.simple_bind_s(user_dn, password)
        return True
    except ldap.INVALID_CREDENTIALS:
        return False
    except ldap.SERVER_DOWN:
        return False
项目:drastic-web    作者:UMD-DRASTIC    | 项目源码 | 文件源码
def ldapAuthenticate(username, password):
    if settings.AUTH_LDAP_SERVER_URI is None:
        return False

    if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
        return False

    try:
        connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
        connection.protocol_version = ldap.VERSION3
        user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
        connection.simple_bind_s(user_dn, password)
        return True
    except ldap.INVALID_CREDENTIALS:
        return False
    except ldap.SERVER_DOWN:
        # TODO: Return error instead of none
        return False
项目:drastic-web    作者:UMD-DRASTIC    | 项目源码 | 文件源码
def ldapAuthenticate(username, password):
    if settings.AUTH_LDAP_SERVER_URI is None:
        return False

    if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
        return False

    try:
        connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
        connection.protocol_version = ldap.VERSION3
        user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
        connection.simple_bind_s(user_dn, password)
        return True
    except ldap.INVALID_CREDENTIALS:
        return False
    except ldap.SERVER_DOWN:
        return False
项目:pizza-auth    作者:xxpizzaxx    | 项目源码 | 文件源码
def check_credentials(self, username, password):
        try:
            ldap_client = ldap.initialize(self.config["server"])
            ldap_client.set_option(ldap.OPT_REFERRALS,0)
            ldap_client.simple_bind_s("uid=%s,%s" % (username, self.config["memberdn"]), password)
        except ldap.INVALID_DN_SYNTAX:
            ldap_client.unbind()
            return False
        except ldap.INVALID_CREDENTIALS:
            ldap_client.unbind()
            return False
        except ldap.UNWILLING_TO_PERFORM:
            ldap_client.unbind()
            return False
        except ldap.SERVER_DOWN:
            ldap_client.unbind()
            raise ServerDownException()
            return False
        ldap_client.unbind()
        return True
项目:Splunk_TA_LDAP    作者:f33dy0urhe4d    | 项目源码 | 文件源码
def reconnect(self,uri):
    # Drop and clean up old connection completely
    # Reconnect
    reconnect_counter = self._retry_max
    while reconnect_counter:
      if __debug__ and self._trace_level>=1:
        self._trace_file.write('*** Try %d. reconnect to %s...\n' % (
          self._retry_max-reconnect_counter+1,uri
        ))
      try:
        # Do the connect
        self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri)
        self._restore_options()
        # StartTLS extended operation in case this was called before
        if self._start_tls:
          self.start_tls_s()
        # Repeat last simple or SASL bind
        self._apply_last_bind()
      except ldap.SERVER_DOWN,e:
        SimpleLDAPObject.unbind_s(self)
        del self._l
        if __debug__ and self._trace_level>=1:
          self._trace_file.write('*** %d. reconnect to %s failed\n' % (
            self._retry_max-reconnect_counter+1,uri
          ))
        reconnect_counter = reconnect_counter-1
        if not reconnect_counter:
          raise
        if __debug__ and self._trace_level>=1:
          self._trace_file.write('=> delay %s...\n' % (self._retry_delay))
        time.sleep(self._retry_delay)
      else:
        if __debug__ and self._trace_level>=1:
          self._trace_file.write('*** %d. reconnect to %s successful, last operation will be repeated\n' % (
            self._retry_max-reconnect_counter+1,uri
          ))
        self._reconnects_done = self._reconnects_done + 1L
        break
项目:Splunk_TA_LDAP    作者:f33dy0urhe4d    | 项目源码 | 文件源码
def _apply_method_s(self,func,*args,**kwargs):
    if not self.__dict__.has_key('_l'):
       self.reconnect(self._uri)
    try:
      return func(self,*args,**kwargs)
    except ldap.SERVER_DOWN:
      SimpleLDAPObject.unbind_s(self)
      del self._l
      # Try to reconnect
      self.reconnect(self._uri)
      # Re-try last operation
      return func(self,*args,**kwargs)
项目:Splunk_TA_LDAP    作者:f33dy0urhe4d    | 项目源码 | 文件源码
def reconnect(self,uri):
    # Drop and clean up old connection completely
    # Reconnect
    reconnect_counter = self._retry_max
    while reconnect_counter:
      if __debug__ and self._trace_level>=1:
        self._trace_file.write('*** Try %d. reconnect to %s...\n' % (
          self._retry_max-reconnect_counter+1,uri
        ))
      try:
        # Do the connect
        self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri)
        self._restore_options()
        # StartTLS extended operation in case this was called before
        if self._start_tls:
          self.start_tls_s()
        # Repeat last simple or SASL bind
        self._apply_last_bind()
      except ldap.SERVER_DOWN,e:
        SimpleLDAPObject.unbind_s(self)
        del self._l
        if __debug__ and self._trace_level>=1:
          self._trace_file.write('*** %d. reconnect to %s failed\n' % (
            self._retry_max-reconnect_counter+1,uri
          ))
        reconnect_counter = reconnect_counter-1
        if not reconnect_counter:
          raise
        if __debug__ and self._trace_level>=1:
          self._trace_file.write('=> delay %s...\n' % (self._retry_delay))
        time.sleep(self._retry_delay)
      else:
        if __debug__ and self._trace_level>=1:
          self._trace_file.write('*** %d. reconnect to %s successful, last operation will be repeated\n' % (
            self._retry_max-reconnect_counter+1,uri
          ))
        self._reconnects_done = self._reconnects_done + 1L
        break
项目:Splunk_TA_LDAP    作者:f33dy0urhe4d    | 项目源码 | 文件源码
def _apply_method_s(self,func,*args,**kwargs):
    if not self.__dict__.has_key('_l'):
       self.reconnect(self._uri)
    try:
      return func(self,*args,**kwargs)
    except ldap.SERVER_DOWN:
      SimpleLDAPObject.unbind_s(self)
      del self._l
      # Try to reconnect
      self.reconnect(self._uri)
      # Re-try last operation
      return func(self,*args,**kwargs)
项目:rucio    作者:rucio01    | 项目源码 | 文件源码
def initiate_ldap():
    """
    contact the LDAP server to return a LDAP object
    """
    ldap_schemes = ['ldap://', 'ldaps://']
    ldap.set_option(ldap.OPT_DEBUG_LEVEL, 0)
    ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, config.get('ldap', 'cacertdir'))
    ldap.set_option(ldap.OPT_X_TLS_CERTFILE, config.get('ldap', 'certfile'))
    ldap.set_option(ldap.OPT_X_TLS_KEYFILE, config.get('ldap', 'keyfile'))
    ldap.set_option(ldap.OPT_X_TLS_DEMAND, True)
    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND)  # TRY, NEVER, DEMAND
    ldap.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
    for scheme in ldap_schemes:
        ldap_url = scheme + server_url
        ldap_obj = ldap.initialize(ldap_url)
        try:
            ldap_obj.start_tls_s()
        except ldap.OPERATIONS_ERROR as e:
            e_msg = e[0]['info']
            if e_msg == 'TLS already started':
                pass
            else:
                raise
        except ldap.SERVER_DOWN:
            if scheme is not ldap_schemes[-1]:
                continue
            else:
                raise
        if login_dn != 'DEFAULT':  # Use anonymous bind if login_dn is set as DEFAULT
            ldap_obj.bind(login_dn, password, ldap.AUTH_SIMPLE)
        else:
            try:
                ldap_obj.whoami_s()
            except ldap.UNWILLING_TO_PERFORM:
                print 'Anonymous binding is disabled by server'
                raise SystemExit
        return ldap_obj
        break
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def _apply_last_bind(self):
    if self._last_bind!=None:
      func,args,kwargs = self._last_bind
      func(self,*args,**kwargs)
    else:
      # Send explicit anon simple bind request to provoke ldap.SERVER_DOWN in method reconnect()
      SimpleLDAPObject.simple_bind_s(self,'','')
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def _apply_method_s(self,func,*args,**kwargs):
    if '_l' not in self.__dict__:
      self.reconnect(self._uri,retry_max=self._retry_max,retry_delay=self._retry_delay)
    try:
      return func(self,*args,**kwargs)
    except ldap.SERVER_DOWN:
      SimpleLDAPObject.unbind_s(self)
      del self._l
      # Try to reconnect
      self.reconnect(self._uri,retry_max=self._retry_max,retry_delay=self._retry_delay)
      # Re-try last operation
      return func(self,*args,**kwargs)
项目:ccs-twistedextensions    作者:apple    | 项目源码 | 文件源码
def test_server_down_auth(self):
        """
        Verify an ldap.SERVER_DOWN error will retry 2 more times and that
        the connection is closed if all attempts fail.
        """
        service = self.service()

        testStats = {}
        # Verify that without a SERVER_DOWN we don't need to retry, and we
        # still have a connection in the pool
        service._authenticateUsernamePassword_inThread(
            u"uid=wsanchez,cn=user,{0}".format(self.baseDN),
            u"zehcnasw",
            testStats=testStats
        )
        self.assertEquals(testStats["retryNumber"], 0)
        self.assertEquals(len(service.connectionPools["auth"].connections), 1)

        testStats["raise"] = ldap.SERVER_DOWN

        # Now try auth again
        try:
            service._authenticateUsernamePassword_inThread(
                u"uid=wsanchez,cn=user,{0}".format(self.baseDN),
                u"zehcnasw",
                testStats=testStats
            )
        except LDAPQueryError:
            # Verify the number of times we retried
            self.assertEquals(testStats["retryNumber"], 2)
        except:
            self.fail("Should have raised LDAPQueryError")
项目:iris    作者:linkedin    | 项目源码 | 文件源码
def ldap_auth(self, username, password):
        ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)
        connection = ldap.initialize(self.ldap_url)
        connection.set_option(ldap.OPT_REFERRALS, 0)

        try:
            if password:
                connection.simple_bind_s(username + self.user_suffix, password)
            else:
                return False
        except ldap.INVALID_CREDENTIALS:
            return False
        except ldap.SERVER_DOWN:
            return None
        return True
项目:pyldap_orm    作者:asyd    | 项目源码 | 文件源码
def test_server_down(self):
        with pytest.raises(ldap.SERVER_DOWN):
            session = pyldap_orm.LDAPSession(backend='ldap://localhost:1')
            session.authenticate()
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
def __init__(self, username, password):
        ldap_host = "192.168.78.8"
        ldap_port = "389"
        ldaps_port = "636"
        ldap_enable_ldaps = False
        self.ldap_base_dn = "DC=example,DC=com,DC=cn"  # example.com.cn

        self.ldap_user = username
        self.ldap_password = password

        if ldap_enable_ldaps is True:
            self.uri = "ldaps://" + ldap_host + ":" + ldaps_port
        else:
            self.uri = "ldap://" + ldap_host + ":" + ldap_port

        self.is_active = False
        self.user_data = None

        self.conn = ldap.initialize(self.uri)

        try:
            self.conn.set_option(ldap.OPT_REFERRALS, 0)  # this option is required in Windows Server 2012
            self.conn.simple_bind_s(who=self.ldap_user, cred=self.ldap_password)
        except ldap.INVALID_CREDENTIALS:
            raise Exception("Invalid credentials")
        except ldap.SERVER_DOWN:
            raise Exception("Can't contact LDAP server")

        self.is_active = True
        self.user_data = self.conn.search_s(self.ldap_base_dn, ldap.SCOPE_SUBTREE,
                                            'userPrincipalName=' + self.ldap_user)
        # self.user_data = self.conn.search_s(self.ldap_base_dn, ldap.SCOPE_SUBTREE)
        self.conn.unbind()
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def reconnect(self,uri,retry_max=1,retry_delay=60.0):
    # Drop and clean up old connection completely
    # Reconnect
    self._reconnect_lock.acquire()
    try:
      reconnect_counter = retry_max
      while reconnect_counter:
        counter_text = '%d. (of %d)' % (retry_max-reconnect_counter+1,retry_max)
        if __debug__ and self._trace_level>=1:
          self._trace_file.write('*** Trying %s reconnect to %s...\n' % (
            counter_text,uri
          ))
        try:
          # Do the connect
          self._l = ldap.functions._ldap_function_call(ldap._ldap_module_lock,_ldap.initialize,uri)
          self._restore_options()
          # StartTLS extended operation in case this was called before
          if self._start_tls:
            SimpleLDAPObject.start_tls_s(self)
          # Repeat last simple or SASL bind
          self._apply_last_bind()
        except (ldap.SERVER_DOWN,ldap.TIMEOUT):
          if __debug__ and self._trace_level>=1:
            self._trace_file.write('*** %s reconnect to %s failed\n' % (
              counter_text,uri
            ))
          reconnect_counter = reconnect_counter-1
          if not reconnect_counter:
            raise
          if __debug__ and self._trace_level>=1:
            self._trace_file.write('=> delay %s...\n' % (retry_delay))
          time.sleep(retry_delay)
          SimpleLDAPObject.unbind_s(self)
          del self._l
        else:
          if __debug__ and self._trace_level>=1:
            self._trace_file.write('*** %s reconnect to %s successful => repeat last operation\n' % (
              counter_text,uri
            ))
          self._reconnects_done = self._reconnects_done + 1
          break
    finally:
      self._reconnect_lock.release()
    return # reconnect()
项目:ccs-twistedextensions    作者:apple    | 项目源码 | 文件源码
def test_server_down(self):
        """
        Verify an ldap.SERVER_DOWN error will retry 2 more times and that
        the connection is closed if all attempts fail.
        """

        service = self.service()

        testStats = {}
        # Verify that without a SERVER_DOWN we don't need to retry, and we
        # still have a connection in the pool
        service._recordsFromQueryString_inThread("(this=that)", testStats=testStats)
        self.assertEquals(testStats["retryNumber"], 0)
        self.assertEquals(len(service.connectionPools["query"].connections), 1)

        service._recordWithDN_inThread("cn=test", testStats=testStats)
        self.assertEquals(testStats["retryNumber"], 0)
        self.assertEquals(len(service.connectionPools["query"].connections), 1)

        # Force a search to raise SERVER_DOWN
        def raiseServerDown(*args, **kwds):
            raise ldap.SERVER_DOWN
        self.patch(LDAPObject, "search_ext", raiseServerDown)
        self.patch(LDAPObject, "search_s", raiseServerDown)

        # Now try recordsFromQueryString
        try:
            service._recordsFromQueryString_inThread("(this=that)", testStats=testStats)
        except LDAPQueryError:
            # Verify the number of times we retried
            self.assertEquals(testStats["retryNumber"], 2)
        except:
            self.fail("Should have raised LDAPQueryError")

        # Verify the connections are all closed
        self.assertEquals(len(service.connectionPools["query"].connections), 0)

        # Now try recordWithDN
        try:
            service._recordWithDN_inThread("cn=test", testStats=testStats)
        except LDAPQueryError:
            # Verify the number of times we retried
            self.assertEquals(testStats["retryNumber"], 2)
        except:
            self.fail("Should have raised LDAPQueryError")

        # Verify the connections are all closed
        self.assertEquals(len(service.connectionPools["query"].connections), 0)
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def open_ldap():
    """
    Returns a freshly made LDAP object, according to the settings
    configured in webfront.conf.
    """
    # Get config settings
    server = _config.get('ldap', 'server')
    port = _config.getint('ldap', 'port')
    encryption = _config.get('ldap', 'encryption').lower()
    timeout = _config.getfloat('ldap', 'timeout')
    # Revert to no encryption if none of the valid settings are found
    if encryption not in ('ssl', 'tls', 'none'):
        _logger.warning('Unknown encryption setting %r in config file, '
                        'using no encryption instead',
                        _config.get('ldap', 'encryption'))
        encryption = 'none'

    # Debug tracing from python-ldap/openldap to stderr
    if _config.getboolean('ldap', 'debug'):
        ldap.set_option(ldap.OPT_DEBUG_LEVEL, 255)

    # Use STARTTLS if enabled, then fail miserably if the server
    # does not support it
    if encryption == 'tls':
        _logger.debug("Using STARTTLS for ldap connection")
        lconn = ldap.open(server, port)
        lconn.timeout = timeout
        try:
            lconn.start_tls_s()
        except ldap.PROTOCOL_ERROR:
            _logger.error('LDAP server %s does not support the STARTTLS '
                          'extension.  Aborting.', server)
            raise NoStartTlsError(server)
        except (ldap.SERVER_DOWN, ldap.CONNECT_ERROR):
            _logger.exception("LDAP server is down")
            raise NoAnswerError(server)
    else:
        scheme = encryption == 'ssl' and 'ldaps' or 'ldap'
        uri = '%s://%s:%s' % (scheme, server, port)
        lconn = ldap.initialize(uri)
        lconn.timeout = timeout

    return lconn
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def authenticate(login, password):
    """
    Attempt to authenticate the login name with password against the
    configured LDAP server.  If the user is authenticated, required
    group memberships are also verified.
    """
    lconn = open_ldap()
    server = _config.get('ldap', 'server')
    user = LDAPUser(login, lconn)
    # Bind to user using the supplied password
    try:
        user.bind(password)
    except (ldap.SERVER_DOWN, ldap.CONNECT_ERROR):
        _logger.exception("LDAP server is down")
        raise NoAnswerError(server)
    except ldap.INVALID_CREDENTIALS:
        _logger.warning("Server %s reported invalid credentials for user %s",
                        server, login)
        return False
    except ldap.TIMEOUT as error:
        _logger.error("Timed out waiting for LDAP bind operation")
        raise TimeoutError(error)
    except ldap.LDAPError:
        _logger.exception("An LDAP error occurred when authenticating user %s "
                          "against server %s", login, server)
        return False
    except UserNotFound:
        _logger.exception("Username %s was not found in the LDAP catalog %s",
                          login, server)
        return False

    _logger.debug("LDAP authenticated user %s", login)

    # If successful so far, verify required group memberships before
    # the final verdict is made
    group_dn = _config.get('ldap', 'require_group')
    if group_dn:
        if user.is_group_member(group_dn):
            _logger.info("%s is verified to be a member of %s",
                         login, group_dn)
            return user
        else:
            _logger.warning("Could NOT verify %s as a member of %s",
                            login, group_dn)
            return False

    # If no group matching was needed, we are already authenticated,
    # so return that.
    return user
项目:ipa_check_consistency    作者:peterpakos    | 项目源码 | 文件源码
def __init__(self, fqdn, binddn, bindpw):
        self._log = logging.getLogger()
        self._log.debug('Initialising FreeIPA server %s' % fqdn)
        self.fqdn = fqdn
        self.hostname_short = fqdn.partition('.')[0]
        self._domain = fqdn.partition('.')[2]
        self._binddn = binddn
        self._bindpw = bindpw
        self._url = 'ldaps://' + fqdn
        self._base_dn = 'dc=' + fqdn.partition('.')[2].replace('.', ',dc=')
        self._active_user_base = 'cn=users,cn=accounts,' + self._base_dn
        self._stage_user_base = 'cn=staged users,cn=accounts,cn=provisioning,' + self._base_dn
        self._preserved_user_base = 'cn=deleted users,cn=accounts,cn=provisioning,' + self._base_dn
        self._groups_base = 'cn=groups,cn=accounts,' + self._base_dn

        try:
            self._conn = ldap.initialize(self._url)
            self._conn.set_option(ldap.OPT_NETWORK_TIMEOUT, 3)
            self._conn.simple_bind_s(self._binddn, self._bindpw)
        except (
            ldap.SERVER_DOWN,
            ldap.NO_SUCH_OBJECT,
            ldap.INVALID_CREDENTIALS
        ) as err:
            self._log.critical('Bind error: %s (%s)' % (err.message['desc'], self.fqdn))
            exit(1)

        self.users = self._count_users(user_base='active')
        self.ustage = self._count_users(user_base='stage')
        self.upres = self._count_users(user_base='preserved')
        self.ugroups = self._count_groups()
        self.hosts = self._count_hosts()
        self.hgroups = self._count_hostgroups()
        self.hbac = self._count_hbac_rules()
        self.sudo = self._count_sudo_rules()
        self.zones = self._count_dns_zones()
        self.certs = self._count_certificates()
        self.ldap = self._ldap_conflicts()
        self.ghosts = self._ghost_replicas()
        self.bind = self._anon_bind()
        self.msdcs = self._ms_adtrust()
        self.replica, self.healthy_agreements = self._replication_agreements()