本文整理匯總了Python中ldap.modlist方法的典型用法代碼示例。如果您正苦於以下問題:Python ldap.modlist方法的具體用法?Python ldap.modlist怎麽用?Python ldap.modlist使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ldap
的用法示例。
在下文中一共展示了ldap.modlist方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: add
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def add(self):
"""Add the group to LDAP."""
try:
ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
"(objectClass=*)", None)
emsg = "A group with this name already exists"
raise errors.InvalidConfigError(emsg)
except ldap.NO_SUCH_OBJECT:
pass
ldif = {
"objectClass": [b"posixGroup", b"top"],
"cn": [b(self.name)],
"gidNumber": [b(str(self.gid))]
}
if self.users:
ldif["memberUid"] = [b(u) for u in self.users]
ldif = ldap.modlist.addModlist(ldif)
signals.emit("groups", "pre_add", self)
conns.LDAP.add_s(self.ldap_id, ldif)
signals.emit("groups", "post_add", self)
示例2: ldap_update_user
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def ldap_update_user(self, uid, old, new):
"""
修改dap用戶
:param uid: 用戶名
:param old: 原屬性 {'mail': ['admin@example.com']}
:param new 新屬性 {'mail': ['root@example.com']}
:return: True/None
"""
result = None
try:
obj = self.ldapconn
obj.protocal_version = ldap.VERSION3
dn = "uid=%s,%s" % (uid, BASE_DN)
ldif = modlist.modifyModlist(old, new)
obj.modify_s(dn, ldif)
obj.unbind_s()
result = True
except ldap.LDAPError as e:
logger.error("修改用戶%s 失敗,原因為: %s" % (uid, str(e)))
return result
示例3: update
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def update(self, newpasswd=""):
"""
Update a user's object in LDAP. Change params on the object first.
To change password, do so via the ``newpasswd`` param here.
:param str newpasswd: new password to set
"""
try:
ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
"(objectClass=*)", None)
except ldap.NO_SUCH_OBJECT:
raise errors.InvalidConfigError(
"Users", "This user does not exist")
self.mail = list(set(self.mail))
for i, x in enumerate(self.mail):
if not x.endswith(self.domain):
self.mail[i] = x.split("@")[0] + "@" + self.domain
ldif = ldif[0][1]
attrs = {
"givenName": [b(self.first_name)],
"sn": [b(self.last_name)] if self.last_name else [b"NONE"],
"displayName": [b(self.full_name)],
"cn": [b(self.full_name)],
"mail": [b(x) for x in self.mail]
}
if newpasswd:
attrs["userPassword"] = [b(ldap_sha512_crypt.encrypt(newpasswd))]
signals.emit("users", "pre_update", self)
nldif = ldap.modlist.modifyModlist(ldif, attrs, ignore_oldexistent=1)
conns.LDAP.modify_s(self.ldap_id, nldif)
self.update_adminsudo()
self.update_samba(newpasswd)
signals.emit(
"users", "post_update", {"user": self, "passwd": newpasswd}
)
示例4: update_adminsudo
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def update_adminsudo(self):
"""Update the user's admin and sudo group settings in LDAP."""
ldif = conns.LDAP.search_s(
"cn=admins,ou=groups,{0}".format(self.rootdn),
ldap.SCOPE_SUBTREE, "(objectClass=*)", None)[0][1]
memlist = ldif["member"]
ldif_vals = [(1, "member", None), (0, "member", memlist)]
if self.admin and b(self.ldap_id) not in memlist:
memlist += [b(self.ldap_id)]
conns.LDAP.modify_s(
"cn=admins,ou=groups,{0}".format(self.rootdn), ldif_vals)
elif not self.admin and self.ldap_id in memlist:
memlist.remove(self.ldap_id)
conns.LDAP.modify_s(
"cn=admins,ou=groups,{0}".format(self.rootdn), ldif_vals)
try:
conns.LDAP.search_s(
"cn={0},ou=sudo,{1}".format(
self.name, self.rootdn),
ldap.SCOPE_SUBTREE, "(objectClass=*)", None)
is_sudo = True
except ldap.NO_SUCH_OBJECT:
is_sudo = False
if self.sudo and not is_sudo:
nldif = {
"objectClass": [b"sudoRole", b"top"],
"cn": [b(self.name)],
"sudoHost": b"ALL",
"sudoCommand": b"ALL",
"sudoUser": [b(self.name)],
"sudoOption": b"authenticate"
}
nldif = ldap.modlist.addModlist(nldif)
conns.LDAP.add_s(
"cn=" + self.name + ",ou=sudo," + self.rootdn, nldif)
elif not self.sudo and is_sudo:
conns.LDAP.delete_s(
"cn=" + self.name + ",ou=sudo," + self.rootdn)
示例5: update
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def update(self):
"""Update a group object in LDAP. Change params on the object first."""
try:
ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
"(objectClass=*)", None)
except ldap.NO_SUCH_OBJECT:
raise errors.InvalidConfigError("This group does not exist")
ldif = ldap.modlist.modifyModlist(
ldif[0][1], {"memberUid": [b(u) for u in self.users]},
ignore_oldexistent=1)
signals.emit("groups", "pre_update", self)
conns.LDAP.modify_s(self.ldap_id, ldif)
signals.emit("groups", "post_update", self)
示例6: _set_password
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def _set_password(self, name, password, by_cn=True):
unicode_pass = '\"' + password + '\"'
password_value = unicode_pass.encode('utf-16-le')
ldap_client = self._bind()
if by_cn:
dn = self._byte_p2('CN=%(cn)s,%(user_dn)s' % {
'cn': name,
'user_dn': self.userdn
})
else:
dn = self._byte_p2(name)
attrs = {}
attrs['unicodePwd'] = self._modlist(self._byte_p2(password_value))
ldif = modlist.modifyModlist({'unicodePwd': 'tmp'}, attrs)
ldap_client.modify_s(dn, ldif)
del(attrs['unicodePwd'])
attrs['UserAccountControl'] = self._modlist(
self._tobyte(NORMAL_ACCOUNT)
)
ldif = modlist.modifyModlist({'UserAccountControl': 'tmp'}, attrs)
ldap_client.modify_s(dn, ldif)
示例7: add_user
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def add_user(self, attrs):
"""add a user"""
ldap_client = self._bind()
# encoding crap
attrs_srt = self.attrs_pretreatment(attrs)
attrs_srt[self._byte_p2('objectClass')] = self.objectclasses
# construct is DN
dn = \
self._byte_p2(self.dn_user_attr) + \
self._byte_p2('=') + \
self._byte_p2(ldap.dn.escape_dn_chars(
attrs[self.dn_user_attr]
)
) + \
self._byte_p2(',') + \
self._byte_p2(self.userdn)
# gen the ldif first add_s and add the user
ldif = modlist.addModlist(attrs_srt)
try:
ldap_client.add_s(dn, ldif)
except ldap.ALREADY_EXISTS as e:
raise UserAlreadyExists(attrs[self.key], self.backend_name)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s()
示例8: ldap_add_user
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def ldap_add_user(self, cn, mail, username, password):
"""
添加ldap用戶
:param cn: 中文名, mail: 郵箱, username: 用戶名, password: 密碼
:return: True/None
"""
result = None
try:
obj = self.ldapconn
obj.protocal_version = ldap.VERSION3
password_encrypt = pass_encrypt(password)
addDN = "uid=%s,%s" % (username, BASE_DN)
attrs = {}
attrs['objectclass'] = ['inetOrgPerson'.encode('utf-8')]
attrs['cn'] = [str(cn).encode('utf-8')]
# attrs['homeDirectory'] = str('/home/%s' % username)
# attrs['loginShell'] = '/bin/bash'
attrs['mail'] = [str(mail).encode('utf-8')]
attrs['sn'] = [str(username).encode('utf-8')]
attrs['uid'] = [str(username).encode('utf-8')]
attrs['userPassword'] = [str(password_encrypt).encode('utf-8')]
# attrs['uidNumber'] = str(self.__get_max_uidNumber())
# attrs['gidNumber'] = self.__ldap_getgid(cn='員工')
ldif = ldap.modlist.addModlist(attrs)
obj.add_s(addDN, ldif)
obj.unbind_s()
result = True
except ldap.LDAPError as e:
logger.error("生成用戶%s 失敗,原因為: %s" % (username, str(e)))
return result
示例9: create_security_group
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def create_security_group(bind, dn, name):
dn = 'CN=' + name + ',' + dn
attrs = {}
attrs['objectClass'] = ['top', 'group']
attrs['name'] = name
# the groupType value may differ between ldap systems
# this value can be found with an ldap browser
attrs['groupType'] = '-2147483640'
attrs['cn'] = name
attrs['sAMAccountName'] = name
print(attrs)
ldif = modlist.addModlist(attrs)
print(ldif)
new_security_group = bind.add_s(dn, ldif)
return new_security_group
示例10: create_ou
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def create_ou(bind, dn, name):
dn = 'OU=' + name + ',' + dn
attrs = {}
attrs['objectClass'] = ['top', 'organizationalUnit']
attrs['name'] = name
print(attrs)
ldif = modlist.addModlist(attrs)
print(ldif)
new_ou = bind.add_s(dn, ldif)
return new_ou
示例11: add
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def add(self, passwd):
"""
Add the user to LDAP.
:param str passwd: user password to set
"""
try:
ldif = conns.LDAP.search_s(
self.ldap_id, ldap.SCOPE_BASE, "(objectClass=*)", None)
msg = "A user named {0} already exists".format(self.name)
raise errors.InvalidConfigError(msg)
except ldap.NO_SUCH_OBJECT:
pass
# Create LDAP user with proper metadata
ldif = {
"objectClass": [b"mailAccount", b"inetOrgPerson", b"posixAccount"],
"givenName": [b(self.first_name)],
"sn": [b(self.last_name)] if self.last_name else [b"NONE"],
"displayName": [b(self.full_name)],
"cn": [b(self.full_name)],
"uid": [b(self.name)],
"mail": [b(self.name + "@" + self.domain)],
"maildrop": [b(self.name)],
"userPassword": [b(ldap_sha512_crypt.encrypt(passwd))],
"gidNumber": [b"100"],
"uidNumber": [b(str(self.uid))],
"homeDirectory": [b("/home/" + self.name)],
"loginShell": [b"/usr/bin/bash"]
}
ldif = ldap.modlist.addModlist(ldif)
signals.emit("users", "pre_add", self)
logger.debug("Roles", "Adding user: {0}".format(self.ldap_id))
conns.LDAP.add_s(self.ldap_id, ldif)
modes = ["admin" if self.admin else "", "sudo" if self.sudo else ""]
msg = "Setting user modes: {0}".format(", ".join(modes))
logger.debug("Roles", msg)
self.update_adminsudo()
self.update_samba(passwd)
signals.emit("users", "post_add", {"user": self, "passwd": passwd})
示例12: set_attrs
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def set_attrs(self, username, attrs):
""" set user attributes"""
ldap_client = self._bind()
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
dn = self._byte_p2(tmp[0])
old_attrs = tmp[1]
for attr in attrs:
bcontent = self._byte_p2(attrs[attr])
battr = self._byte_p2(attr)
new = {battr: self._modlist(self._byte_p3(bcontent))}
# if attr is dn entry, use rename
if attr.lower() == self.dn_user_attr.lower():
ldap_client.rename_s(
dn,
ldap.dn.dn2str([[(battr, bcontent, 1)]])
)
dn = ldap.dn.dn2str(
[[(battr, bcontent, 1)]] + ldap.dn.str2dn(dn)[1:]
)
else:
# if attr is already set, replace the value
# (see dict old passed to modifyModlist)
if attr in old_attrs:
if type(old_attrs[attr]) is list:
tmp = []
for value in old_attrs[attr]:
tmp.append(self._byte_p2(value))
bold_value = tmp
else:
bold_value = self._modlist(
self._byte_p3(old_attrs[attr])
)
old = {battr: bold_value}
# attribute is not set, just add it
else:
old = {}
ldif = modlist.modifyModlist(old, new)
if ldif:
try:
ldap_client.modify_s(dn, ldif)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s()
示例13: add_to_groups
# 需要導入模塊: import ldap [as 別名]
# 或者: from ldap import modlist [as 別名]
def add_to_groups(self, username, groups):
ldap_client = self._bind()
# recover dn of the user and his attributes
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
dn = tmp[0]
attrs = tmp[1]
attrs['dn'] = dn
self._normalize_group_attrs(attrs)
dn = self._byte_p2(tmp[0])
# add user to all groups
for group in groups:
group = self._byte_p2(group)
# iterate on group membership attributes
for attr in self.group_attrs:
# fill the content template
content = self._byte_p2(self.group_attrs[attr] % attrs)
self._logger(
severity=logging.DEBUG,
msg="%(backend)s: adding user '%(user)s'"
" with dn '%(dn)s' to group '%(group)s' by"
" setting '%(attr)s' to '%(content)s'" % {
'user': username,
'dn': self._uni(dn),
'group': self._uni(group),
'attr': attr,
'content': self._uni(content),
'backend': self.backend_name
}
)
ldif = modlist.modifyModlist(
{},
{attr: self._modlist(self._byte_p3(content))}
)
try:
ldap_client.modify_s(group, ldif)
# if already member, not a big deal, just log it and continue
except (ldap.TYPE_OR_VALUE_EXISTS, ldap.ALREADY_EXISTS) as e:
self._logger(
severity=logging.INFO,
msg="%(backend)s: user '%(user)s'"
" already member of group '%(group)s'"
" (attribute '%(attr)s')" % {
'user': username,
'group': self._uni(group),
'attr': attr,
'backend': self.backend_name
}
)
except ldap.NO_SUCH_OBJECT as e:
raise GroupDoesntExist(group, self.backend_name)
except Exception as e:
ldap_client.unbind_s()
self._exception_handler(e)
ldap_client.unbind_s()