本文整理汇总了Python中ldap.filter方法的典型用法代码示例。如果您正苦于以下问题:Python ldap.filter方法的具体用法?Python ldap.filter怎么用?Python ldap.filter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ldap
的用法示例。
在下文中一共展示了ldap.filter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: search_with_additional_terms
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def search_with_additional_terms(self, term_dict, escape=True):
"""
Returns a new search object with additional search terms and-ed to the
filter string. term_dict maps attribute names to assertion values. If
you don't want the values escaped, pass escape=False.
"""
term_strings = [self.filterstr]
for name, value in term_dict.items():
if escape:
value = self.ldap.filter.escape_filter_chars(value)
term_strings.append("({}={})".format(name, value))
filterstr = "(&{})".format("".join(term_strings))
return type(self)(self.base_dn, self.scope, filterstr, attrlist=self.attrlist)
示例2: _escape_filterargs
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def _escape_filterargs(self, filterargs):
"""
Escapes values in filterargs.
filterargs is a value suitable for Django's string formatting operator
(%), which means it's either a tuple or a dict. This return a new tuple
or dict with all values escaped for use in filter strings.
"""
if isinstance(filterargs, tuple):
filterargs = tuple(
self.ldap.filter.escape_filter_chars(value) for value in filterargs
)
elif isinstance(filterargs, dict):
filterargs = {
key: self.ldap.filter.escape_filter_chars(value)
for key, value in filterargs.items()
}
else:
raise TypeError("filterargs must be a tuple or dict.")
return filterargs
示例3: ldap_search
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [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
示例4: search_a_user
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def search_a_user(self, user_search_string=None, search_by='all_fields'):
os.environ["KRB5_CLIENT_KTNAME"] = self.FREEIPA_KTNAME
size_limit = 50
if user_search_string and search_by == 'all_fields':
filter = ldap.filter.filter_format("(&(|(givenName=*%s*)(sn=*%s*)(uid=*%s*)(mail=*%s*))(|(nsaccountlock=FALSE)(!(nsaccountlock=*))))", [user_search_string] * 4)
elif user_search_string and search_by == 'username_only':
filter = ldap.filter.filter_format("(&(uid=%s)(|(nsaccountlock=FALSE)(!(nsaccountlock=*))))", [user_search_string])
size_limit = 1
else:
filter = '(objectclass=person)'
searchParameters = {'search_base': self.FREEIPA_USER_SEARCH_BASE,
'search_filter': filter,
'attributes': ['uid', 'sn', 'givenName', 'mail'],
'size_limit': size_limit}
self.conn.search(**searchParameters)
users = []
for idx, entry in enumerate(self.conn.entries, 1):
user_dict = self.parse_ldap_entry(entry)
users.append(user_dict)
logger.info("LDAP user search for %s found %s results", user_search_string, len(users))
return users
示例5: search_a_user
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def search_a_user(self, user_search_string=None, search_by='all_fields'):
size_limit = 50
if user_search_string and search_by == 'all_fields':
filter = ldap.filter.filter_format("(|(givenName=*%s*)(sn=*%s*)(uid=*%s*)(mail=*%s*))", [user_search_string] * 4)
elif user_search_string and search_by == 'username_only':
filter = ldap.filter.filter_format("(uid=%s)", [user_search_string])
size_limit = 1
else:
filter = '(objectclass=person)'
searchParameters = {'search_base': self.LDAP_USER_SEARCH_BASE,
'search_filter': filter,
'attributes': ['uid', 'sn', 'givenName', 'mail'],
'size_limit': size_limit}
self.conn.search(**searchParameters)
users = []
for idx, entry in enumerate(self.conn.entries, 1):
user_dict = self.parse_ldap_entry(entry)
users.append(user_dict)
logger.info("LDAP user search for %s found %s results", user_search_string, len(users))
return users
示例6: ad_recursive_groups
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [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
示例7: revoke_privilege
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def revoke_privilege(self):
"""
Revoke all privileges from a user
"""
user = User.query.filter(User.username == self.username).first()
if user:
user_id = user.id
try:
DomainUser.query.filter(DomainUser.user_id == user_id).delete()
db.session.commit()
return True
except Exception as e:
db.session.rollback()
current_app.logger.error(
'Cannot revoke user {0} privileges. DETAIL: {1}'.format(
self.username, e))
return False
return False
示例8: get_groups
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def get_groups(self, username):
username = ldap.filter.escape_filter_chars(username)
userdn = self._get_user(self._byte_p2(username), NO_ATTR)
searchfilter = self.group_filter_tmpl % {
'userdn': userdn,
'username': username
}
groups = self._search_group(searchfilter, self.groupdn)
groups = groups + self._search_group(searchfilter, self.builtin)
ret = []
self._logger(
severity=logging.DEBUG,
msg="%(backend)s: groups of '%(user)s' are %(groups)s" % {
'user': username,
'groups': str(groups),
'backend': self.backend_name
}
)
for entry in groups:
ret.append(self._uni(entry[1]['cn'][0]))
return ret
示例9: get_groups_with_wildcard
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def get_groups_with_wildcard(self, groups_wildcard):
self.logger.info("Search group with wildcard: %s" % groups_wildcard)
filter = self.group_filter % groups_wildcard
result_groups = []
result = self.conn.search_s(base=self.base,
scope=ldap.SCOPE_SUBTREE,
filterstr=filter, )
for group in result:
# Skip refldap (when Active Directory used)
# [0]==None
if group[0]:
group_name = group[1]['name'][0]
self.logger.info("Find group %s" % group_name)
result_groups.append(group_name)
if not result_groups:
self.logger.info('Unable to find group "%s", skipping group wildcard' % groups_wildcard)
return result_groups
示例10: search_with_additional_term_string
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def search_with_additional_term_string(self, filterstr):
"""
Returns a new search object with filterstr and-ed to the original filter
string. The caller is responsible for passing in a properly escaped
string.
"""
filterstr = "(&{}{})".format(self.filterstr, filterstr)
return type(self)(self.base_dn, self.scope, filterstr, attrlist=self.attrlist)
示例11: execute
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def execute(self, connection, filterargs=(), escape=True):
"""
Executes the search on the given connection (an LDAPObject). filterargs
is an object that will be used for expansion of the filter string.
If escape is True, values in filterargs will be escaped.
The python-ldap library returns utf8-encoded strings. For the sake of
sanity, this method will decode all result strings and return them as
Unicode.
"""
if escape:
filterargs = self._escape_filterargs(filterargs)
try:
filterstr = self.filterstr % filterargs
results = connection.search_s(
self.base_dn, self.scope, filterstr, self.attrlist
)
except ldap.LDAPError as e:
results = []
logger.error(
"search_s('{}', {}, '{}') raised {}".format(
self.base_dn, self.scope, filterstr, pprint.pformat(e)
)
)
return self._process_results(results)
示例12: _begin
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def _begin(self, connection, filterargs=(), escape=True):
"""
Begins an asynchronous search and returns the message id to retrieve
the results.
filterargs is an object that will be used for expansion of the filter
string. If escape is True, values in filterargs will be escaped.
"""
if escape:
filterargs = self._escape_filterargs(filterargs)
try:
filterstr = self.filterstr % filterargs
msgid = connection.search(
self.base_dn, self.scope, filterstr, self.attrlist
)
except ldap.LDAPError as e:
msgid = None
logger.error(
"search('{}', {}, '{}') raised {}".format(
self.base_dn, self.scope, filterstr, pprint.pformat(e)
)
)
return msgid
示例13: find_groups_with_any_member
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def find_groups_with_any_member(self, member_dn_set, group_search, connection):
terms = [
"({}={})".format(self.member_attr, self.ldap.filter.escape_filter_chars(dn))
for dn in member_dn_set
]
filterstr = "(|{})".format("".join(terms))
search = group_search.search_with_additional_term_string(filterstr)
return search.execute(connection)
示例14: get_user_info_by_username
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def get_user_info_by_username(self):
user_info = User.query.filter(User.username == self.username).first()
return user_info
示例15: create_local_user
# 需要导入模块: import ldap [as 别名]
# 或者: from ldap import filter [as 别名]
def create_local_user(self):
"""
Create local user witch stores username / password in the DB
"""
# check if username existed
user = User.query.filter(User.username == self.username).first()
if user:
return {'status': False, 'msg': 'Username is already in use'}
# check if email existed
user = User.query.filter(User.email == self.email).first()
if user:
return {'status': False, 'msg': 'Email address is already in use'}
# first register user will be in Administrator role
self.role_id = Role.query.filter_by(name='User').first().id
if User.query.count() == 0:
self.role_id = Role.query.filter_by(
name='Administrator').first().id
self.password = self.get_hashed_password(
self.plain_text_password) if self.plain_text_password else '*'
if self.password and self.password != '*':
self.password = self.password.decode("utf-8")
db.session.add(self)
db.session.commit()
return {'status': True, 'msg': 'Created user successfully'}