本文整理匯總了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