Python 和 LDAP
2010-09-22 11:12:52 来源:WEB开发网通过 mod_auth_ldap 模块向 Apache 提供 LDAP 身份验证,此模块是在 Fedora Core 8 httpd 包中默认安装的。对于试图登录的用户,要求在 'stooges' 组织中包含有效的电子邮件地址和密码,这样才能访问上面定义的 Apache 虚拟主机。请注意 AuthLDAPURL 指令,它指定通过 LDAP 服务器实现用户身份验证所用的查询。我们搜索 'mail' 属性并应用过滤器 (o=stooges)。AuthLDAPURL 指令的完整语法请参见 http://httpd.apache.org/docs/2.0/mod/mod_auth_ldap.html#authldapurl。
用 Python-LDAP 执行 CRUD 操作
现在,准备使用 Python 与 LDAP 交互。为此,必须安装 python-ldap 模块。在 参考资料 中,可以找到关于安装此模块的详细信息的链接。实际上,只需要执行 “easy install”。首先下载 easy_install 脚本:
http://peak.telecommunity.com/dist/ez_setup.py
然后输入:
sudo easy_install python-ldap
注意,根据操作系统的不同,此包依赖的一些软件略有差异。如果在安装此包时遇到问题,请仔细阅读安装说明。
安装 python-ldap 之后,就可以执行 CRUD 操作了。下面编写一个执行这些操作的类。
Python LDAP CRUD 类
#!/bin/env python
import sys, ldap
LDAP_HOST = 'localhost'
LDAP_BASE_DN = 'dc=unisonis,dc=com'
MGR_CRED = 'cn=Manager,dc=unisonis,dc=com'
MGR_PASSWD = 'mypasswd'
STOOGE_FILTER = 'o=stooges'
class StoogeLDAPMgmt:
def __init__(self, ldap_host=None, ldap_base_dn=None, mgr_cred=None,
mgr_passwd=None):
if not ldap_host:
ldap_host = LDAP_HOST
if not ldap_base_dn:
ldap_base_dn = LDAP_BASE_DN
if not mgr_cred:
mgr_cred = MGR_CRED
if not mgr_passwd:
mgr_passwd = MGR_PASSWD
self.ldapconn = ldap.open(ldap_host)
self.ldapconn.simple_bind(mgr_cred, mgr_passwd)
self.ldap_base_dn = ldap_base_dn
def list_stooges(self, stooge_filter=None, attrib=None):
if not stooge_filter:
stooge_filter = STOOGE_FILTER
s = self.ldapconn.search_s(self.ldap_base_dn, ldap.SCOPE_SUBTREE,
stooge_filter, attrib)
print "Here is the complete list of stooges:"
stooge_list = []
for stooge in s:
attrib_dict = stooge[1]
for a in attrib:
out = "%s: %s" % (a, attrib_dict[a])
print out
stooge_list.append(out)
return stooge_list
def add_stooge(self, stooge_name, stooge_ou, stooge_info):
stooge_dn = 'cn=%s,ou=%s,%s' % (stooge_name, stooge_ou, self.ldap_base_dn)
stooge_attrib = [(k, v) for (k, v) in stooge_info.items()]
print "Adding stooge %s with ou=%s" % (stooge_name, stooge_ou)
self.ldapconn.add_s(stooge_dn, stooge_attrib)
def modify_stooge(self, stooge_name, stooge_ou, stooge_attrib):
stooge_dn = 'cn=%s,ou=%s,%s' % (stooge_name, stooge_ou, self.ldap_base_dn)
print "Modifying stooge %s with ou=%s" % (stooge_name, stooge_ou)
self.ldapconn.modify_s(stooge_dn, stooge_attrib)
def delete_stooge(self, stooge_name, stooge_ou):
stooge_dn = 'cn=%s,ou=%s,%s' % (stooge_name, stooge_ou, self.ldap_base_dn)
print "Deleting stooge %s with ou=%s" % (stooge_name, stooge_ou)
self.ldapconn.delete_s(stooge_dn)
更多精彩
赞助商链接