本文整理汇总了Python中ldap3.Connection方法的典型用法代码示例。如果您正苦于以下问题:Python ldap3.Connection方法的具体用法?Python ldap3.Connection怎么用?Python ldap3.Connection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ldap3
的用法示例。
在下文中一共展示了ldap3.Connection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: try_ldap_login
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [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
示例2: useruid
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def useruid(s, login):
"""Connect to a LDAP and check the uid matching the given field data"""
uid = False
c = Connection(s, config.LDAPACC,
password=config.LDAPPASS, auto_bind=True)
if c.result["description"] != "success":
app.logger.error("Error connecting to the LDAP with the service account")
return False
# Look for the user entry.
if not c.search(config.LDAPBASE,
"(" + config.LDAPFIELD + "=" + login + ")") :
app.logger.error("Error: Connection to the LDAP with service account failed")
else:
if len(c.entries) >= 1 :
if len(c.entries) > 1 :
app.logger.error("Error: multiple entries with this login. "+ \
"Trying first entry...")
uid = c.entries[0].entry_dn
else:
app.logger.error("Error: Login not found")
c.unbind()
return uid
示例3: make_connection
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def make_connection(self, bind_user=None, bind_password=None, app=None, **kwargs):
"""
Make a connection to the LDAP Directory.
Args:
bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is
used, otherwise authentication specified with
config['LDAP_BIND_AUTHENTICATION_TYPE'] is used.
bind_password (str): Password to bind to the directory with
**kwargs (dict): Additional arguments to pass to the
``ldap3.Connection``
Returns:
ldap3.Connection: An unbound ldap3.Connection. You should handle exceptions
upon bind if you use this internal method.
"""
return self._make_connection(
bind_user, bind_password, contextualise=False, app=app, **kwargs
)
示例4: _contextualise_connection
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def _contextualise_connection(self, connection):
"""
Add a connection to the appcontext so it can be freed/unbound at
a later time if an exception occured and it was not freed.
Args:
connection (ldap3.Connection): Connection to add to the appcontext
"""
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, "ldap3_manager_connections"):
ctx.ldap3_manager_connections = [connection]
else:
ctx.ldap3_manager_connections.append(connection)
示例5: get_user_info
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def get_user_info(self, dn, _connection=None):
"""
Gets info about a user specified at dn.
Args:
dn (str): The dn of the user to find
_connection (ldap3.Connection): A connection object to use when
searching. If not given, a temporary connection will be
created, and destroyed after use.
Returns:
dict: A dictionary of the user info from LDAP
"""
return self.get_object(
dn=dn,
filter=current_app.config.get("LDAP_USER_OBJECT_FILTER"),
attributes=current_app.config.get("LDAP_GET_USER_ATTRIBUTES"),
_connection=_connection,
)
示例6: get_group_info
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def get_group_info(self, dn, _connection=None):
"""
Gets info about a group specified at dn.
Args:
dn (str): The dn of the group to find
_connection (ldap3.Connection): A connection object to use when
searching. If not given, a temporary connection will be
created, and destroyed after use.
Returns:
dict: A dictionary of the group info from LDAP
"""
return self.get_object(
dn=dn,
filter=current_app.config.get("LDAP_GROUP_OBJECT_FILTER"),
attributes=current_app.config.get("LDAP_GET_GROUP_ATTRIBUTES"),
_connection=_connection,
)
示例7: valid_user
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def valid_user(self, user_dn, password):
conn = ldap3.Connection(
self._server, user=user_dn, password=password, check_names=True, lazy=False, raise_exceptions=False
)
try:
conn.open()
except Exception as e:
log.e(str(e))
return TPE_FAILED, '无法连接到LDAP服务器'
conn.bind()
if not (
('result' in conn.result and 0 == conn.result['result'])
and
('description' in conn.result and 'success' == conn.result['description'])
):
return TPE_USER_AUTH, '认证失败'
return TPE_OK, ''
示例8: main
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [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
示例9: connect
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [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)
示例10: __init__
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [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())
示例11: check
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [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
示例12: get_user_attributes_from_ldap
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def get_user_attributes_from_ldap(ldap_connection, ldap_base_dn, login, attribute):
"""returns the user group names, no permissions for now
:param ldap3.Connection ldap_connection: The ldap_client as ldap3.Connection instance
:param str ldap_base_dn: The domain name in LDAP format (all this CN, DN stuff)
:param str login: The login
:param str attribute: The attribute to query
"""
result = []
if ldap_connection:
ldap_filter = '(sAMAccountName=%s)' % login
result = ldap_connection.search(
ldap_base_dn,
ldap_filter,
attributes=attribute,
)
if result:
data = ldap_connection.response
return data[0]['attributes'][attribute]
return None
示例13: start_tls
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def start_tls(self):
assert(isinstance(self.conn, ldap3.Connection))
if self.config['START_TLS']:
logger = logging.getLogger("realms.auth.ldap")
try:
self.conn.open()
except ldap3.LDAPSocketOpenError as ex:
logger.exception("Error when connecting to LDAP server")
return False
try:
return self.conn.start_tls()
except ldap3.LDAPStartTLSError as ex:
logger.exception("START_TLS error")
return False
except Exception as ex:
logger.exception("START_TLS unexpectedly failed")
return False
return True
示例14: connect
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def connect(self, user, password, anonymous=False):
auto_bind_strategy = AUTO_BIND_TLS_BEFORE_BIND
authentication_policy = SIMPLE
if current_app.config['LDAP_USE_TLS'] is not True:
auto_bind_strategy = AUTO_BIND_NO_TLS
if anonymous:
authentication_policy = ANONYMOUS
user = None
password = None
ldap_conn = Connection(
self.ldap_server,
auto_bind=auto_bind_strategy,
client_strategy=current_app.config['LDAP_CONNECTION_STRATEGY'],
raise_exceptions=current_app.config['LDAP_RAISE_EXCEPTIONS'],
authentication=authentication_policy,
user=user,
password=password,
check_names=True,
read_only=current_app.config['LDAP_READ_ONLY'],
)
return ldap_conn
示例15: _remove_dn_from_proid_group
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import Connection [as 别名]
def _remove_dn_from_proid_group(self, conn, server_dn, proid, force=False):
"""Removes a placement.
:param conn:
The `ldap3.Connection`
:param server_dn:
The server server_dn
:param proid:
The name of the proid
"""
server_dn_set = self._get_server_dn_set(proid)
if not force:
if not self._decrement_dn(server_dn_set, server_dn):
return
group = self._config.get_group_dn(proid)
_LOGGER.debug('Removing %r from group %r', server_dn, group)
conn.modify(group, {'member': [(ldap3.MODIFY_DELETE,
[server_dn])]})
if not _check_ldap3_operation(conn) and not force:
self._increment_dn(server_dn_set, server_dn)