本文整理汇总了Python中ldap.LDAPError方法的典型用法代码示例。如果您正苦于以下问题:Python ldap.LDAPError方法的具体用法?Python ldap.LDAPError怎么用?Python ldap.LDAPError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ldap
的用法示例。
在下文中一共展示了ldap.LDAPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_auth_signal_ldap_error
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def test_auth_signal_ldap_error(self):
self._init_settings(
BIND_DN="uid=bob,ou=people,o=test",
BIND_PASSWORD="bogus",
USER_SEARCH=LDAPSearch(
"ou=people,o=test", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
),
)
def handle_ldap_error(sender, **kwargs):
raise kwargs["exception"]
with catch_signal(ldap_error) as handler:
handler.side_effect = handle_ldap_error
with self.assertRaises(ldap.LDAPError):
authenticate(username="alice", password="password")
handler.assert_called_once()
_args, kwargs = handler.call_args
self.assertEqual(kwargs["context"], "authenticate")
示例2: exact
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def exact(self):
try:
results = self.connection.search_s(
self.dn, ldap.SCOPE_BASE, attrlist=[self.name])
except ldap.LDAPError:
e = get_exception()
self.module.fail_json(
msg="Cannot search for attribute %s" % self.name,
details=str(e))
current = results[0][1].get(self.name, [])
modlist = []
if frozenset(self.values) != frozenset(current):
if len(current) == 0:
modlist = [(ldap.MOD_ADD, self.name, self.values)]
elif len(self.values) == 0:
modlist = [(ldap.MOD_DELETE, self.name, None)]
else:
modlist = [(ldap.MOD_REPLACE, self.name, self.values)]
return modlist
示例3: _connect_to_ldap
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [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
示例4: _ldap_connect
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [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
示例5: ldap_search
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def ldap_search(self, ldap_filter, base=None, scope=ldap.SCOPE_SUBTREE):
if not base:
base = self.plugin_settings().get(["search_base"])
try:
client = self.get_ldap_client()
if client is not None:
self._logger.debug("Searching LDAP, base: %s and filter: %s" % (base, ldap_filter))
result = client.search_s(base, scope, ldap_filter)
client.unbind_s()
if result:
dn, data = result[0]
"""
# Dump LDAP search query results to logger
self._logger.debug("dn: %s" % dn)
for key, value in data.iteritems():
self._logger.debug("%s: %s" % (key, value))
"""
return dict(dn=dn, data=data)
except ldap.LDAPError as e:
self._logger.error(json.dumps(e.message))
return None
示例6: getDefaultNamingContext
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [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: find_and_remove_pubkeys
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def find_and_remove_pubkeys(self, login, password, pattern):
"""Find and remove public keys of the user with the ``login`` that maches the ``pattern``.
Arguments:
login (str): Login of the user to add the ``pubkey``.
password (Optional[str]): The user's password to bind with, or None
to not (re)bind with the user's credentials.
pattern (str): The pattern specifying public keys to be removed.
Raises:
UserEntryNotFoundError: If the ``login`` is not found.
NoPubKeyFoundError: If no public key matching the ``pattern`` is found.
InsufficientAccessError: If the bind user doesn't have rights to add the pubkey.
ldap.LDAPError:
Returns:
List[str]: A list of removed public keys.
"""
dn = self.find_dn_by_login(login)
if password:
self._bind(dn, password)
pubkeys = [key for key in self._find_pubkeys(dn) if pattern in key]
for key in pubkeys:
self._remove_pubkey(dn, key)
return pubkeys
示例8: clean
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def clean(self):
super().clean()
host = self.cleaned_data.get("host")
bind_dn = self.cleaned_data.get("bind_dn")
bind_password = self.cleaned_data.get("bind_password")
if host and bind_dn and bind_password:
try:
conn = get_ldap_connection(host)
except ldap.LDAPError as e:
e_dict = e.args[0]
self.add_error("host", e_dict.get("desc", e_dict.get("info", str(e))))
except Exception as e:
self.add_error("host", str(e))
else:
try:
conn.simple_bind_s(bind_dn, bind_password)
except ldap.LDAPError as e:
e_dict = e.args[0]
self.add_error("bind_password", e_dict.get("desc", e_dict.get("info", str(e))))
except Exception as e:
self.add_error("bind_password", str(e))
示例9: _ldap_user_search_with_rdn
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def _ldap_user_search_with_rdn(self, conn, username_or_email, user_search_dn, suffix=""):
query = "(|({0}={2}{3})({1}={2}{3}))".format(
self._uid_attr, self._email_attr, escape_filter_chars(username_or_email), suffix
)
query = self._add_user_filter(query)
logger.debug("Conducting user search: %s under %s", query, user_search_dn)
try:
return (conn.search_s(user_search_dn, ldap.SCOPE_SUBTREE, query), None)
except ldap.REFERRAL as re:
referral_dn = self._get_ldap_referral_dn(re)
if not referral_dn:
return (None, "Failed to follow referral when looking up username")
try:
subquery = "(%s=%s)" % (self._uid_attr, username_or_email)
subquery = self._add_user_filter(subquery)
return (conn.search_s(referral_dn, ldap.SCOPE_BASE, subquery), None)
except ldap.LDAPError:
logger.debug("LDAP referral search exception")
return (None, "Username not found")
except ldap.LDAPError:
logger.debug("LDAP search exception")
return (None, "Username not found")
示例10: validate_ldap
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def validate_ldap(self):
'Validate the username/password data against ldap directory'
ldap_mgr = current_app.ldap_login_manager
username = self.username.data
password = self.password.data
try:
userdata = ldap_mgr.ldap_login(username, password)
except ldap.INVALID_CREDENTIALS:
flash("Invalid LDAP credentials", 'danger')
return False
except ldap.LDAPError as err:
if isinstance(err.message, dict):
message = err.message.get('desc', str(err))
else:
message = str(err.message)
flash(message, 'danger')
return False
if userdata is None:
flash("Invalid LDAP credentials", 'danger')
return False
self.user = ldap_mgr._save_user(username, userdata)
return True
示例11: ad_recursive_groups
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def ad_recursive_groups(self, groupDN):
"""
Recursively list groups belonging to a group. It will allow checking deep in the Active Directory
whether a user is allowed to enter or not
"""
LDAP_BASE_DN = Setting().get('ldap_base_dn')
groupSearchFilter = "(&(objectcategory=group)(member=%s))" % ldap.filter.escape_filter_chars(
groupDN)
result = [groupDN]
try:
groups = self.ldap_search(groupSearchFilter, LDAP_BASE_DN)
for group in groups:
result += [group[0][0]]
if 'memberOf' in group[0][1]:
for member in group[0][1]['memberOf']:
result += self.ad_recursive_groups(
member.decode("utf-8"))
return result
except ldap.LDAPError as e:
current_app.logger.exception("Recursive AD Group search error")
return result
示例12: __ldap_getgid
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def __ldap_getgid(self, cn="员工"):
"""
查询 组cn对应的gid
:param cn: 组cn
:return: 对应cn的gidNumber
"""
obj = self.ldapconn
obj.protocal_version = ldap.VERSION3
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = None
searchFilter = "cn=" + cn
try:
ldap_result_id = obj.search(
base="%s" % self.base_dn,
scope=searchScope,
filterstr=searchFilter,
attrlist=retrieveAttributes
)
result_type, result_data = obj.result(ldap_result_id, 0)
if result_type == ldap.RES_SEARCH_ENTRY:
return result_data[0][1].get('gidNumber')[0]
else:
return None
except ldap.LDAPError as e:
logger.error('获取gid失败,原因为: %s' % str(e))
示例13: check_user_belong_to_group
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def check_user_belong_to_group(self, uid, group_cn='员工'):
"""
查询 用户 是否归属于某个组
:param uid: 用户uid , Ex: 'ssoadmin'
:param group_cn: 归属组cn , Ex: '黑名单'
:return: True|None
"""
result = None
try:
search = self.ldap_search_dn(value=group_cn, value_type='cn')
if search is None:
raise ldap.LDAPError('未查询到相应 id')
member_list = search[0][1].get('memberUid', [])
if uid in member_list:
result = True
except ldap.LDAPError as e:
logger.error('获取用户%s与组%s关系失败,原因为: %s' % (uid, group_cn, str(e)))
return result
示例14: check_user_status
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def check_user_status(self, uid):
"""
验证用户状态
:param uid: 用户uid
:return: 200: 用户可用
404: 用户不存在
403: 用户被禁用
"""
result = 404
data = None
try:
target_cn = self.ldap_get_user(uid=uid)
if target_cn is None: # 如未查到用户,记录日志,但不算错误,后边有很多地方会验证用户是否存在
result = 404
logger.debug("%s uid未查询到" % uid)
else:
if self.check_user_belong_to_group(uid=uid, group_cn='黑名单'):
result = 403
else:
result, data = 200, target_cn
except ldap.LDAPError as e:
logger.error("%s 检查用户状态失败,原因为: %s" % (uid, str(e)))
return 500
return result, data
示例15: ldap_update_password
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import LDAPError [as 别名]
def ldap_update_password(self, uid, new_password=None, old_password=None):
"""
更新密码
:param uid: 用户uid,新password
:return: True|None
"""
result = None
try:
obj = self.ldapconn
obj.protocal_version = ldap.VERSION3
modifyDN = "uid=%s,%s" % (uid, BASE_DN)
new_password_encrypt = pass_encrypt(new_password)
#有old_password情况下
if old_password:
obj.passwd_s(modifyDN, [str(old_password).encode('utf-8')], [new_password_encrypt.encode('utf-8')])
result = True
else:
obj.modify_s(modifyDN, [(ldap.MOD_REPLACE, 'userPassword', [new_password_encrypt.encode('utf-8')])])
result = True
obj.unbind_s()
except ldap.LDAPError as e:
logger.error("%s 密码更新失败,原因为: %s" % (uid, str(e)))
return False
return result