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


Python ldap3.Server方法代码示例

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


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

示例1: try_ldap_login

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def try_ldap_login(login, password):
    """ Connect to a LDAP directory to verify user login/passwords"""
    result = "Wrong login/password"
    s = Server(config.LDAPURI, port=config.LDAPPORT,
               use_ssl=False, get_info=ALL)
    # 1. connection with service account to find the user uid
    uid = useruid(s, login)
   
    if uid: 
        # 2. Try to bind the user to the LDAP
        c = Connection(s, user = uid , password = password, auto_bind = True)
        c.open()
        c.bind()
        result =  c.result["description"] # "success" if bind is ok
        c.unbind()

    return result 
开发者ID:LibrIT,项目名称:passhport,代码行数:19,代码来源:user.py

示例2: _bind

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def _bind(self):
        if not self.i_am_bound:
            if not self.serverpool:
                self.serverpool = self.get_serverpool_instance(self.get_info)
            self.l = self.create_connection(authtype=self.authtype,
                                            server=self.serverpool,
                                            user=self.binddn,
                                            password=self.bindpw,
                                            receive_timeout=self.timeout,
                                            auto_referrals=not
                                            self.noreferrals,
                                            start_tls=self.start_tls)
            #log.error("LDAP Server Pool States: %s" % server_pool.pool_states)
            if not self.l.bind():
                raise Exception("Wrong credentials")
            self.i_am_bound = True 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:18,代码来源:LDAPIdResolver.py

示例3: add_server

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def add_server(self, hostname, port, use_ssl, tls_ctx=None, app=None):
        """
        Add an additional server to the server pool and return the
        freshly created server.

        Args:
            hostname (str): Hostname of the server
            port (int): Port of the server
            use_ssl (bool): True if SSL is to be used when connecting.
            tls_ctx (ldap3.Tls): An optional TLS context object to use
                when connecting.
            app (flask.Flask): The app on which to add the server. If not
                given, ``flask.current_app`` is used.

        Returns:
            ldap3.Server: The freshly created server object.
        """
        if app is None:
            app = current_app._get_current_object()
        if not use_ssl and tls_ctx:
            raise ValueError("Cannot specify a TLS context and not use SSL!")
        server = ldap3.Server(hostname, port=port, use_ssl=use_ssl, tls=tls_ctx)
        app.ldap3_login_manager_server_pool.add(server)
        return server 
开发者ID:nickw444,项目名称:flask-ldap3-login,代码行数:26,代码来源:__init__.py

示例4: initialize_server

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def initialize_server(host, port, secure_connection, unsecure):
    """
    uses the instance configuration to initialize the LDAP server

    :param host: host or ip
    :type host: string
    :param port: port or None
    :type port: number
    :param secure_connection: SSL or None
    :type secure_connection: string
    :param unsecure: trust any cert
    :type unsecure: boolean
    :return: ldap3 Server
    :rtype: Server
    """

    if secure_connection == "SSL":
        # intialize server with ssl
        # port is configured by default as 389 or as 636 for LDAPS if not specified in configuration
        demisto.debug("initializing sever with ssl (unsecure: {}). port: {}". format(unsecure, port or 'default(636)'))
        if not unsecure:
            demisto.debug("will require server certificate.")
            tls = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=os.environ.get('SSL_CERT_FILE'))
            if port:
                return Server(host, port=port, use_ssl=True, tls=tls)
            return Server(host, use_ssl=True, tls=tls)
        if port:
            return Server(host, port=port, use_ssl=True)
        return Server(host, use_ssl=True)
    demisto.debug("initializing server without secure connection. port: {}". format(port or 'default(389)'))
    if port:
        return Server(host, port=port)
    return Server(host) 
开发者ID:demisto,项目名称:content,代码行数:35,代码来源:Active_Directory_Query.py

示例5: main

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def main():
        # Create the Server object with the given address.
        server = Server(LDAP_SERVER, get_info=ALL)
        #Create a connection object, and bind with the given DN and password.
        try: 
                conn = Connection(server, LDAP_USER, LDAP_PASSWORD, auto_bind=True)
                print('LDAP Bind Successful.')
                # Perform a search for a pre-defined criteria.
                # Mention the search filter / filter type and attributes.
                conn.search('dc=demo1,dc=freeipa,dc=org', LDAP_FILTER , attributes=LDAP_ATTRS)
                # Print the resulting entries.
                for entry in conn.entries:
                        print(entry)
        except core.exceptions.LDAPBindError as e:
                # If the LDAP bind failed for reasons such as authentication failure.
                print('LDAP Bind Failed: ', e) 
开发者ID:PacktPublishing,项目名称:Learning-Python-Networking-Second-Edition,代码行数:18,代码来源:entries_ldap_server.py

示例6: connect

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [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

示例7: __init__

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def __init__(self, user_search_string, search_by):
        super().__init__(user_search_string, search_by)
        self.FREEIPA_SERVER = import_from_settings('FREEIPA_SERVER')
        self.FREEIPA_USER_SEARCH_BASE = import_from_settings('FREEIPA_USER_SEARCH_BASE', 'cn=users,cn=accounts')
        self.FREEIPA_KTNAME = import_from_settings('FREEIPA_KTNAME', '')

        self.server = Server('ldap://{}'.format(self.FREEIPA_SERVER), use_ssl=True, connect_timeout=1)
        if len(self.FREEIPA_KTNAME) > 0:
            logger.info('Kerberos bind enabled: %s', self.FREEIPA_KTNAME)
            # kerberos SASL/GSSAPI bind
            os.environ["KRB5_CLIENT_KTNAME"] = self.FREEIPA_KTNAME
            self.conn = Connection(self.server, authentication=SASL, sasl_mechanism=KERBEROS, auto_bind=True)
        else:
            # anonomous bind
            self.conn = Connection(self.server, auto_bind=True)

        if not self.conn.bind():
            raise ImproperlyConfigured('Failed to bind to LDAP server: {}'.format(self.conn.result))
        else:
            logger.info('LDAP bind successful: %s', self.conn.extend.standard.who_am_i()) 
开发者ID:ubccr,项目名称:coldfront,代码行数:22,代码来源:search.py

示例8: sendAuth

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def sendAuth(self, authenticateMessageBlob, serverChallenge=None):
        if unpack('B', str(authenticateMessageBlob)[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:
            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
            token = respToken2['ResponseToken']
        else:
            token = authenticateMessageBlob
        with self.session.connection_lock:
            self.authenticateMessageBlob = token
            request = bind.bind_operation(self.session.version, 'SICILY_RESPONSE_NTLM', self, None)
            response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
            result = response[0]
        self.session.sasl_in_progress = False

        if result['result'] == RESULT_SUCCESS:
            self.session.bound = True
            self.session.refresh_server_info()
            return None, STATUS_SUCCESS
        else:
            if result['result'] == RESULT_STRONGER_AUTH_REQUIRED and self.PLUGIN_NAME != 'LDAPS':
                raise LDAPRelayClientException('Server rejected authentication because LDAP signing is enabled. Try connecting with TLS enabled (specify target as ldaps://hostname )')
        return None, STATUS_ACCESS_DENIED

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
开发者ID:Ridter,项目名称:Exchange2domain,代码行数:25,代码来源:ldaprelayclient.py

示例9: create_ldap_connection

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def create_ldap_connection(domain_controller):
    """Create ldap connection object.
    """
    # Disable W0212: Access to a protected member _is_ipv6 of a
    #                client class
    #
    # This is needed because twisted monkey patches socket._is_ipv6
    # and ldap3 code is wrong.
    # pylint: disable=W0212
    ldap3.Server._is_ipv6 = lambda x, y: False
    server = ldap3.Server(domain_controller, mode=ldap3.IP_V4_ONLY)

    return ldap3.Connection(
        server,
        authentication=ldap3.SASL,
        sasl_mechanism='GSSAPI',
        sasl_credentials=(True,),
        client_strategy=ldap3.RESTARTABLE,
        auto_bind=True,
        auto_range=True,
        return_empty_attributes=False
    ) 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:24,代码来源:_servers.py

示例10: test_init

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def test_init(self):
        """Tests init logic."""
        admin_obj = admin.Admin(None, 'dc=test,dc=com')
        admin_obj.write_ldap = ldap3.Connection(
            ldap3.Server('fake'), client_strategy=ldap3.MOCK_SYNC
        )

        admin_obj.init()

        dn_list = [
            arg[0][0] for arg in admin_obj.write_ldap.add.call_args_list
        ]

        self.assertTrue('dc=test,dc=com' in dn_list)
        self.assertTrue('ou=treadmill,dc=test,dc=com' in dn_list)
        self.assertTrue('ou=apps,ou=treadmill,dc=test,dc=com' in dn_list) 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:18,代码来源:admin_test.py

示例11: test_add

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def test_add(self):
        """Tests add logic."""
        admin_obj = admin.Admin(None, 'dc=test,dc=com')
        admin_obj.write_ldap = ldap3.Connection(
            ldap3.Server('fake'), client_strategy=ldap3.MOCK_SYNC
        )

        admin_obj.add(
            'ou=example,dc=test,dc=com',
            'testClass',
            {
                'foo': 1,
                'bar': ['z', 'a'],
                'lot': 2,
                'exp': [3, 4]
            }
        )

        call = admin_obj.write_ldap.add.call_args_list[0][0]
        self.assertEqual(call[0], 'ou=example,dc=test,dc=com')
        self.assertEqual(call[1], 'testClass')
        self.assertEqual(
            [attr for attr in six.iteritems(call[2])],
            [('bar', ['z', 'a']), ('exp', [3, 4]), ('foo', 1), ('lot', 2)]
        ) 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:27,代码来源:admin_test.py

示例12: test_08_resolver_id

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def test_08_resolver_id(self):
        y = SQLResolver()
        y.loadConfig(self.parameters)
        rid1 = y.getResolverId()

        y = SQLResolver()
        param2 = self.parameters.copy()
        param2["Where"] = "1 = 1"
        y.loadConfig(param2)
        rid2 = y.getResolverId()

        # rid1 == rid2, because only the WHERE clause has changed, which does not have any effect on the resolver id!
        self.assertEqual(rid1, rid2)

        y = SQLResolver()
        param3 = self.parameters.copy()
        param3["Server"] = '/tests/../tests/testdata/'
        y.loadConfig(param3)
        rid3 = y.getResolverId()

        # rid1 != rid3, because the connect string has changed
        self.assertNotEqual(rid1, rid3)

        y = SQLResolver()
        param4 = self.parameters.copy()
        param4["poolSize"] = "42"
        y.loadConfig(param4)
        rid4 = y.getResolverId()

        # rid1 != rid4, because the pool size has changed
        self.assertNotEqual(rid1, rid4) 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:33,代码来源:test_lib_resolver.py

示例13: _ldap_login

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def _ldap_login(self, username, password):
        server = ldap3.Server(self.ldap_config.get('server'))
        dn = self.ldap_config.get('dn')
        userattr = self.ldap_config.get('userattr') or 'uid'
        userstring = '{}={},{}'.format(userattr, username, dn)
        with ldap3.Connection(server, user=userstring, password=password) as conn:
            if conn.bind():
                return True
            else:
                return False 
开发者ID:mitre,项目名称:caldera,代码行数:12,代码来源:auth_svc.py

示例14: get_connection

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def get_connection(self, userdn, password):
        server = ldap3.Server(
            self.server_address, port=self.server_port, use_ssl=self.use_ssl
        )
        auto_bind = (
            self.use_ssl and ldap3.AUTO_BIND_TLS_BEFORE_BIND or ldap3.AUTO_BIND_NO_TLS
        )
        conn = ldap3.Connection(
            server, user=userdn, password=password, auto_bind=auto_bind
        )
        return conn 
开发者ID:jupyterhub,项目名称:ldapauthenticator,代码行数:13,代码来源:ldapauthenticator.py

示例15: doLdapLogin

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Server [as 别名]
def doLdapLogin(username, password):
    if LdapServer == None or LdapServer == "":
        return False
    try:
        from ldap3 import Server, Connection, ALL, NTLM
    except ImportError as importException:
        LogError("LDAP3 import not found, run 'sudo pip install ldap3 && sudo pip3 install ldap3'")
        LogError(importException)
        return False

    HasAdmin = False
    HasReadOnly = False
    SplitName = username.split('\\')
    DomainName = SplitName[0]
    DomainName = DomainName.strip()
    AccountName = SplitName[1]
    AccountName = AccountName.strip()
    server = Server(LdapServer, get_info=ALL)
    conn = Connection(server, user='{}\\{}'.format(DomainName, AccountName), password=password, authentication=NTLM, auto_bind=True)
    conn.search('dc=skipfire,dc=local', '(&(objectclass=user)(sAMAccountName='+AccountName+'))', attributes=['memberOf'])
    for user in sorted(conn.entries):
        for group in user.memberOf:
            if group.upper().find("CN="+LdapAdminGroup.upper()) >= 0:
                HasAdmin = True
            elif group.upper().find("CN="+LdapReadOnlyGroup.upper()) >= 0:
                HasReadOnly = True

    session['logged_in'] = HasAdmin or HasReadOnly
    session['write_access'] = HasAdmin
    if HasAdmin:
        LogError("Admin Login via LDAP")
    elif HasReadOnly:
        LogError("Limited Rights Login via LDAP")
    else:
        LogError("No rights for valid login via LDAP")

    return HasAdmin or HasReadOnly

#------------------------------------------------------------------------------- 
开发者ID:jgyates,项目名称:genmon,代码行数:41,代码来源:genserv.py


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