本文整理汇总了Python中ldap.initialize方法的典型用法代码示例。如果您正苦于以下问题:Python ldap.initialize方法的具体用法?Python ldap.initialize怎么用?Python ldap.initialize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ldap
的用法示例。
在下文中一共展示了ldap.initialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _connect_to_ldap
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def _connect_to_ldap(self):
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
connection = ldap.initialize(self.server_uri)
if self.start_tls:
try:
connection.start_tls_s()
except ldap.LDAPError:
e = get_exception()
self.module.fail_json(msg="Cannot start TLS.", details=str(e))
try:
if self.bind_dn is not None:
connection.simple_bind_s(self.bind_dn, self.bind_pw)
else:
connection.sasl_interactive_bind_s('', ldap.sasl.external())
except ldap.LDAPError:
e = get_exception()
self.module.fail_json(
msg="Cannot bind to the server.", details=str(e))
return connection
示例2: _check_ldap_password
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def _check_ldap_password(cn, password):
"""Checks that the given cn/password credentials work on the given CN.
@param cn: Common name to log on
@param password: Password for cn
@return: True on success, False on failure
"""
cnx = ldap.initialize(config['ckanext.ldap.uri'])
try:
cnx.bind_s(cn, password)
except ldap.SERVER_DOWN:
log.error('LDAP server is not reachable')
return False
except ldap.INVALID_CREDENTIALS:
log.debug('Invalid LDAP credentials')
return False
# Fail on empty password
if password == '':
log.debug('Invalid LDAP credentials')
return False
cnx.unbind_s()
return True
示例3: _ldap_connect
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def _ldap_connect(self):
"""
Prepare ldap object for binding phase.
"""
try:
connection = ldap.initialize(self._ldap_uri)
connection.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
connection.set_option(ldap.OPT_REFERRALS,
int(self._chase_referrals))
if self._ldap_uri.startswith('ldaps://'):
# Require server certificate but ignore it's validity. (allow self-signed)
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
if self._use_tls:
# Require TLS connection.
ldap.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
# Require server certificate but ignore it's validity. (allow self-signed)
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
connection.start_tls_s()
LOG.debug('Connection now using TLS')
return connection
except ldap.LDAPError as e:
LOG.debug('(_ldap_connect) LDAP Error: %s : Type %s' % (str(e), type(e)))
return False
示例4: post_ldap_update
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def post_ldap_update(ldap_bind_dn, ldap_bind_pw):
conn = ldap.initialize('ldaps://localhost:1636')
conn.protocol_version = 3
conn.simple_bind_s(ldap_bind_dn, ldap_bind_pw)
result = conn.search_s('ou=appliances,o=gluu',ldap.SCOPE_SUBTREE,'(oxIDPAuthentication=*)',['oxIDPAuthentication'])
dn = result[0][0]
oxIDPAuthentication = json.loads(result[0][1]['oxIDPAuthentication'][0])
config = json.loads(oxIDPAuthentication['config'])
if config['servers'][0]=='localhost:1636' and config['bindDN'].lower()=='cn=directory manager,o=gluu':
config['bindDN'] = 'cn=Directory Manager'
oxIDPAuthentication['config'] = json.dumps(config)
oxIDPAuthentication = json.dumps(oxIDPAuthentication, indent=2)
conn.modify_s(dn, [( ldap.MOD_REPLACE, 'oxIDPAuthentication', oxIDPAuthentication)])
result = conn.search_s('ou=appliances,o=gluu',ldap.SCOPE_SUBTREE,'(oxTrustConfCacheRefresh=*)',['oxTrustConfCacheRefresh'])
dn = result[0][0]
oxTrustConfCacheRefresh = json.loads(result[0][1]['oxTrustConfCacheRefresh'][0])
oxTrustConfCacheRefresh['inumConfig']['bindDN'] = 'cn=Directory Manager'
oxTrustConfCacheRefresh = json.dumps(oxTrustConfCacheRefresh, indent=2)
conn.modify_s(dn, [( ldap.MOD_REPLACE, 'oxTrustConfCacheRefresh', oxTrustConfCacheRefresh)])
示例5: main
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def main():
try:
# Open a connection
ldap_client = ldap.initialize(LDAP_SERVER)
# Set LDAPv3 option
ldap_client.set_option(ldap.OPT_PROTOCOL_VERSION,3)
# Bind/authenticate with a user with appropriate rights
ldap_client.simple_bind("admin",'Secret123')
# Get user attributes defined in LDAP_ATTRS
result = ldap_client.search_s(LDAP_BASE_DN,ldap.SCOPE_SUBTREE,LDAP_FILTER, LDAP_ATTRS)
print(result)
except ldap.INVALID_CREDENTIALS as exception:
ldap_client.unbind()
print('Wrong username or password. '+exception)
except ldap.SERVER_DOWN as exception:
print('LDAP server not available. '+exception)
开发者ID:PacktPublishing,项目名称:Learning-Python-Networking-Second-Edition,代码行数:18,代码来源:connect_python_ldap.py
示例6: getDefaultNamingContext
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
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
示例7: __enter__
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def __enter__(self):
trace_level = 2 if os.environ.get("USERS_DEBUG") == "1" else 0
self._conn = ldap.initialize(self._ldap_uri, trace_level=trace_level)
self._conn.set_option(ldap.OPT_REFERRALS, 1)
self._conn.set_option(
ldap.OPT_NETWORK_TIMEOUT, self._network_timeout or _DEFAULT_NETWORK_TIMEOUT
)
self._conn.set_option(ldap.OPT_TIMEOUT, self._timeout or _DEFAULT_TIMEOUT)
if self._allow_tls_fallback:
logger.debug("TLS Fallback enabled in LDAP")
self._conn.set_option(ldap.OPT_X_TLS_TRY, 1)
self._conn.simple_bind_s(self._user_dn, self._user_pw)
return self._conn
示例8: bind
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def bind():
"""This function will bind to the LDAP instance and return an ldapobject."""
ldapobject = ldap.initialize(url)
ldapobject.bind_s(bind_dn, bind_password)
if verbose:
if is_outfile_specified:
sys.stdout.write("Successfully bound to %s...\n" % url)
else:
sys.stderr.write("Successfully bound to %s...\n" % url)
return ldapobject
# bind()
示例9: verify_passwd
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def verify_passwd(self, passwd):
"""
Validate the provided password against the hash stored in LDAP.
:param str passwd: password to check
"""
try:
c = ldap.initialize("ldap://localhost")
c.simple_bind_s(self.ldap_id, passwd)
data = c.search_s("cn=admins,ou=groups," + self.rootdn,
ldap.SCOPE_SUBTREE, "(objectClass=*)",
["member"])[0][1]["member"]
if b(self.ldap_id) not in data:
return False
return True
except ldap.INVALID_CREDENTIALS:
return False
示例10: check_ldap_password
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def check_ldap_password(cn, password):
'''Checks that the given cn/password credentials work on the given CN.
:param cn: Common name to log on
:param password: Password for cn
:returns: True on success, False on failure
'''
cnx = ldap.initialize(toolkit.config[u'ckanext.ldap.uri'], bytes_mode=False,
trace_level=toolkit.config[u'ckanext.ldap.trace_level'])
try:
cnx.bind_s(cn, password)
except ldap.SERVER_DOWN:
log.error(u'LDAP server is not reachable')
return False
except ldap.INVALID_CREDENTIALS:
log.debug(u'Invalid LDAP credentials')
return False
# Fail on empty password
if password == u'':
log.debug(u'Invalid LDAP credentials')
return False
cnx.unbind_s()
return True
示例11: authenticate_with_ldap
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def authenticate_with_ldap(self, username, password):
ldap_conn = ldap.initialize(current_app.config.get('LDAP_SERVER'))
ldap_conn.protocol_version = 3
ldap_conn.set_option(ldap.OPT_REFERRALS, 0)
if '@' in username:
who = '{0}@{1}'.format(username.split('@')[0], current_app.config.get('LDAP_DOMAIN'))
else:
who = '{0}@{1}'.format(username, current_app.config.get('LDAP_DOMAIN'))
username = username.split('@')[0]
user = self.get_by_username(username)
try:
if not password:
raise ldap.INVALID_CREDENTIALS
ldap_conn.simple_bind_s(who, password)
if not user:
from api.lib.perm.acl.user import UserCRUD
user = UserCRUD.add(username=username, email=who)
return user, True
except ldap.INVALID_CREDENTIALS:
return user, False
示例12: __init__
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def __init__(self, *args, **kwargs):
"""
Implementation of :func:`~kqueen.auth.base.__init__`
"""
super(LDAPAuth, self).__init__(*args, **kwargs)
if not all(hasattr(self, attr) for attr in ['uri', 'admin_dn', '_password']):
msg = 'Failed to configure LDAP, please provide valid LDAP credentials'
logger.error(msg)
raise ImproperlyConfigured(msg)
# Define Kqueen rdn for all dc's
d_names = ldap.dn.explode_dn(self.admin_dn)
dc_list = [dc for dc in d_names if dc.startswith('dc=')]
self.kqueen_dc = ','.join(dc_list)
# Bind connection for Kqueen Read-only user
if self._bind(self.admin_dn, self._password):
self.connection = ldap.initialize(self.uri)
self.connection.simple_bind_s(self.admin_dn, self._password)
self.connection.protocol_version = ldap.VERSION3
else:
msg = 'Failed to bind connection for Kqueen Read-only user'
logger.error(msg)
raise ImproperlyConfigured(msg)
示例13: initialize
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def initialize(self):
"""Initialize a connection to the LDAP server.
:return: LDAP connection object.
"""
try:
conn = ldap.initialize('{0}://{1}:{2}'.format(
current_app.config['LDAP_SCHEMA'],
current_app.config['LDAP_HOST'],
current_app.config['LDAP_PORT']))
conn.set_option(ldap.OPT_NETWORK_TIMEOUT,
current_app.config['LDAP_TIMEOUT'])
conn = self._set_custom_options(conn)
conn.protocol_version = ldap.VERSION3
if current_app.config['LDAP_USE_TLS']:
conn.start_tls_s()
return conn
except ldap.LDAPError as e:
raise LDAPException(self.error(e.args))
示例14: bind
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def bind(self):
"""Attempts to bind to the LDAP server using the credentials of the
service account.
:return: Bound LDAP connection object if successful or ``None`` if
unsuccessful.
"""
conn = self.initialize
try:
conn.simple_bind_s(
current_app.config['LDAP_USERNAME'],
current_app.config['LDAP_PASSWORD'])
return conn
except ldap.LDAPError as e:
raise LDAPException(self.error(e.args))
示例15: _get_conn
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import initialize [as 别名]
def _get_conn(self):
self._log.debug('Setting up LDAP connection')
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
try:
conn = ldap.initialize(self._url)
conn.set_option(ldap.OPT_NETWORK_TIMEOUT, 3)
conn.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
conn.simple_bind_s(self._binddn, self._bindpw)
except (
ldap.SERVER_DOWN,
ldap.NO_SUCH_OBJECT,
ldap.INVALID_CREDENTIALS
) as e:
if hasattr(e, 'message') and 'desc' in e.message:
msg = e.message['desc']
else:
msg = e.args[0]['desc']
self._log.debug('%s (%s)' % (msg, self._url))
return False
self._log.debug('LDAP connection established')
return conn