python+ldap实例

来源:互联网 发布:星星知多少钻石大陆 编辑:程序博客网 时间:2024/05/23 16:25

Python 如何进行域账号的校验?当然是操作ldap.

首先需要安装python-ldap的模块 http://www.python-ldap.org/。 在这里用的是windows系统,当然比较容易,下载地址 http://pypi.python.org/pypi/python-ldap/。

 

安装后在python 的交互环境里输入import ldap 如果没有问题就说明安装成功了。

验证程序:

#!usr/bin/env python#coding: utf-8import osimport sysimport ldapdef login_ldap(username, password):    try:        print("开始执行")        Server = "ldap://127.0.0.1:8000"        baseDN = "dc=domainname,dc=com"        searchScope = ldap.SCOPE_SUBTREE        # 设置过滤属性,这里只显示cn=test的信息         searchFilter = "sAMAccountName=" + username        # 为用户名加上域名         username = 'domainname\\' + username                        # None表示搜索所有属性,['cn']表示只搜索cn属性         retrieveAttributes = None            conn = ldap.initialize(Server)        #非常重要        conn.set_option(ldap.OPT_REFERRALS, 0)        conn.protocol_version = ldap.VERSION3        # 这里用户名是域账号的全名例如domain/name        print conn.simple_bind_s(username, password)        print 'ldap connect successfully'            #调用search方法返回结果id        ldap_result_id = conn.search(baseDN, searchScope, searchFilter, retrieveAttributes)        result_set = []        print ldap_result_id        print("****************")        while 1:            result_type, result_data = conn.result(ldap_result_id, 0)            if(result_data == []):                break            else:                if result_type == ldap.RES_SEARCH_ENTRY:                    result_set.append(result_data)        #print result_set        Name,Attrs = result_set[0][0]        if hasattr(Attrs, 'has_key') and Attrs.has_key('name'):            print("test3")            distinguishedName = Attrs['mail'][0]            #distinguishedName = Attrs['name'][0]            #distinguishedName = Attrs['displayName'][0]            #distinguishedName = Attrs['mail'][0]            #distinguishedName = Attrs['memberOf'][0]            #distinguishedName = Attrs['mailNickname'][0]            #distinguishedName = Attrs['sAMAccountName'][0]            #distinguishedName = Attrs['distinguishedName'][0]            #distinguishedName = Attrs['title'][0]            #distinguishedName = Attrs['department'][0]            #distinguishedName = Attrs['manager'][0]            print "Login Info for user : %s" % distinguishedName            print Attrs['mail'][0]            print Attrs['name'][0]            print Attrs['displayName'][0]            print Attrs['memberOf'][0]            print Attrs['sAMAccountName'][0]            print Attrs['title'][0]            print Attrs['department'][0]                        return distinguishedName        else:            print("in error")            return None    except ldap.LDAPError, e:        print("out error")        print e        return None    if __name__ == "__main__":    username = "username" # ldap中用户名    password = "password" # ldap中密码        login_ldap(username, password)    


 

参考:http://www.cnblogs.com/itech/archive/2011/02/11/1951576.html

python实例26[验证用户是否存在于LDAP Server]

 

需要安装python2.x 和python-LDAP模块。

python-ldap:http://www.python-ldap.org/

python-ldap的windows版本下载:http://pypi.python.org/pypi/python-ldap/

 

python26实例代码:(用来验证某用户是否存在于LDAP Server)

python实例26[验证用户是否存在于LDAP Server]

 

需要安装python2.x 和python-LDAP模块。

python-ldap:http://www.python-ldap.org/

python-ldap的windows版本下载:http://pypi.python.org/pypi/python-ldap/

 

python26实例代码:(用来验证某用户是否存在于LDAP Server)

python实例26[验证用户是否存在于LDAP Server]

 

需要安装python2.x 和python-LDAP模块。

python-ldap:http://www.python-ldap.org/

python-ldap的windows版本下载:http://pypi.python.org/pypi/python-ldap/

 

python26实例代码:(用来验证某用户是否存在于LDAP Server)

import timeimport ldap'''    Need install python-ldap module from:      http://www.python-ldap.org/    For windows OS, you can get the module from:      http://pypi.python.org/pypi/python-ldap/'''ldapuser = "yourusername";#ldapuser = "CN=yourusername,OU=XXX,OU=XXX,DC=XXX,DC=XXXXX,DC=com"ldappass = "youruserpasswd";ldappath = "ldap://yourldapserveriporname:yourldapserverport/";baseDN = "DC=XXX,DC=XXXXX,DC=COM"FoundResult_ServerBusy = "Server is busy"FoundResult_NotFound = "Not Found"FoundResult_Found = "Found"def _validateLDAPUser(user):    try:        l = ldap.initialize(ldappath)        l.protocol_version = ldap.VERSION3        l.simple_bind(ldapuser,ldappass)        searchScope  = ldap.SCOPE_SUBTREE        searchFiltername = "sAMAccountName"        retrieveAttributes = None        searchFilter = '(' + searchFiltername + "=" + user +')'        ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)        result_type, result_data = l.result(ldap_result_id,1)        if(not len(result_data) == 0):          #print result_data          return 1, FoundResult_Found        else:          return 0, FoundResult_NotFound    except ldap.LDAPError, e:        #print e        return 0, FoundResult_ServerBusy    finally:        l.unbind()        del ldef validateLDAPUser(user, trynum = 30):    i = 0    isfound = 0    foundResult = ""    while(i < trynum):        #print "try: " + str(i)        isfound, foundResult = _validateLDAPUser(user)        if(isfound):          break        #time.sleep(60)        i+=1    print "-------------------------------"    print "user is :" + user    print "isfound :" + str(isfound)    print "FoundResult : " + foundResult    return isfound, foundResult


参考:http://www.linuxforum.net/forum/gshowflat.php?Cat=&Board=python&Number=533078&page=1&view=collapsed&sb=5&o=all

用Python的python-ldap模块操作openldap目录服务器的示例代码

下面是搜索目录项的代码
#!/usr/bin/python
#-*- coding:utf-8 -*- #设置源码文件编码为utf-8

import ldap

try:
conn = ldap.open("server_name") #server_name为ldap服务器名
conn.protocol_version = ldap.VERSION3 #设置ldap协议版本
username = "cn=admin,dc=company,dc=com" #用户名
password = "123" #访问密码
conn.simple_bind(username,password) #连接

except ldap.LDAPError, e: #捕获出错信息
print e

baseDN = "dc=employees,dc=company,dc=com" #设置目录的搜索路径起点
searchScope = ldap.SCOPE_SUBTREE #设置可搜索子路径

retrieveAttributes = None #None表示搜索所有属性,['cn']表示只搜索cn属性
searchFilter = "cn=test" #设置过滤属性,这里只显示cn=test的信息

try:
ldap_result_id = conn.search(baseDN,searchScope,searchFilter,retrieveAttributes)
#调用search方法返回结果id
result_set = []
while 1:
result_type, result_data = conn.result(ldap_result_id, 0) #通过结果id返回信息
if result_data == []:
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)

print result_set[0][0][1]['o'][0] #result_set是一个复合列表,需通过索引返回组织单元(o)信息

except ldap.LDAPError, e:
print e

这里采用的是非同步方式,同步方式的连接和搜索命令后有“_s”后缀,如search_s。非同步方式需通过一个结果id来访问目录服务信息。

 

 

下面是一个修改目录信息的示例:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import ldap

try:
conn = ldap.open("server_name")
conn.protocol_version = ldap.VERSION3
username = "cn=admin,dc=company,dc=com"
password = "123"
conn.simple_bind_s(username,password)

except ldap.LDAPError, e:
print e

try:
dn = "cn=test,dc=employees,dc=company,dc=com"
conn.modify_s(dn,[(ldap.MOD_ADD,'mail','test@163.com')]) #增加一个mail属性
except ldap.LDAPError, e:
print e

ldap.MOD_ADD表示增加属性,ldap.MOD_DELETE表示删除属性,ldap.MOD_REPLACE表示修改属性。

 

 

下面是一个增加目录项的示例:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import ldap,ldap.modlist #ldap.modlist是ldap的子模块,用于格式化目录服务的数据项

try:
conn = ldap.open("server_name")
conn.protocol_version = ldap.VERSION3
username = "cn=admin,dc=company,dc=com"
password = "123"
conn.simple_bind_s(username,password)

except ldap.LDAPError, e:
print e

try:
dn = "cn=test,dc=card,dc=company,dc=com"
modlist = ldap.modlist.addModlist({ #格式化目录项,除对象类型要求必填项外,
'cn': ['test'], #其它项可自由增减
'objectClass': ['top', 'person', 'organizationalPerson', 'inetOrgPerson'],
'o': ['\xe5\xb9\xbf\xe5\xb7\x9e'], #这些为utf-8编码的中文
'street': ['\xe5\xb9\xbf\xe5\xb7\x9e'],
'sn': ['tester'],
'mail': ['test@163.com', 'test@21cn.com'],
'homePhone': ['xxxxxxxx'], 'uid': ['test'] })
# print modlist #显示格式化数据项,格式化后是一个元组列表
conn.add_s(dn,modlist) #调用add_s方法添加目录项

except ldap.LDAPError, e:
print e

其实我们也可按格式化后元组列表的形式把目录项直接写到add_s()里,省却转换的步骤。

下面是删除目录项的示例:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import ldap

try:
conn = ldap.open("server_name")
conn.protocol_version = ldap.VERSION3
username = "cn=admin,dc=test,dc=com"
password = "password"
conn.simple_bind_s(username,password)

except ldap.LDAPError, e:
print e

try:
dn = "cn=sale,dc=test,dc=com"
conn.delete_s(dn)

except ldap.LDAPError, e:
print e

参考:http://www.grotan.com/ldap/python-ldap-samples.html#search

python-ldap sample code

  • Bind
  • Add
  • Modify
  • Search
  • Delete

Binding to LDAP Server

Simple Authentication
import ldaptry:l = ldap.open("127.0.0.1")# you should  set this to ldap.VERSION2 if you're using a v2 directoryl.protocol_version = ldap.VERSION3# Pass in a valid username and password to get # privileged directory access.# If you leave them as empty strings or pass an invalid value# you will still bind to the server but with limited privileges.username = "cn=Manager, o=anydomain.com"password  = "secret"# Any errors will throw an ldap.LDAPError exception # or related exception so you can ignore the resultl.simple_bind(username, password)except ldap.LDAPError, e:print e# handle error however you like

Adding entries to an LDAP Directory

Synchrounous add
# import needed modulesimport ldapimport ldap.modlist as modlist# Open a connectionl = ldap.initialize("ldaps://localhost.localdomain:636/")# Bind/authenticate with a user with apropriate rights to add objectsl.simple_bind_s("cn=manager,dc=example,dc=com","secret")# The dn of our new entry/objectdn="cn=replica,dc=example,dc=com" # A dict to help build the "body" of the objectattrs = {}attrs['objectclass'] = ['top','organizationalRole','simpleSecurityObject']attrs['cn'] = 'replica'attrs['userPassword'] = 'aDifferentSecret'attrs['description'] = 'User object for replication using slurpd'# Convert our dict to nice syntax for the add-function using modlist-moduleldif = modlist.addModlist(attrs)# Do the actual synchronous add-operation to the ldapserverl.add_s(dn,ldif)# Its nice to the server to disconnect and free resources when donel.unbind_s()                            

Modify entries in an LDAP Directory

Synchrounous modify
# import needed modulesimport ldapimport ldap.modlist as modlist# Open a connectionl = ldap.initialize("ldaps://localhost.localdomain:636/")# Bind/authenticate with a user with apropriate rights to add objectsl.simple_bind_s("cn=manager,dc=example,dc=com","secret")# The dn of our existing entry/objectdn="cn=replica,dc=example,dc=com" # Some place-holders for old and new valuesold = {'description':'User object for replication using slurpd'}new = {'description':'Bind object used for replication using slurpd'}# Convert place-holders for modify-operation using modlist-moduleldif = modlist.modifyModlist(old,new)# Do the actual modification l.modify_s(dn,ldif)# Its nice to the server to disconnect and free resources when donel.unbind_s()                            

Searching an LDAP Directory

Asynchronous Search
import ldap## first you must open a connection to the servertry:l = ldap.open("127.0.0.1")## searching doesn't require a bind in LDAP V3.  If you're using LDAP v2, set the next line appropriately## and do a bind as shown in the above example.# you can also set this to ldap.VERSION2 if you're using a v2 directory# you should  set the next option to ldap.VERSION2 if you're using a v2 directoryl.protocol_version = ldap.VERSION3except ldap.LDAPError, e:print e# handle error however you like## The next lines will also need to be changed to support your search requirements and directorybaseDN = "ou=Customers, ou=Sales, o=anydomain.com"searchScope = ldap.SCOPE_SUBTREE## retrieve all attributes - again adjust to your needs - see documentation for more optionsretrieveAttributes = None searchFilter = "cn=*jack*"try:ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)result_set = []while 1:result_type, result_data = l.result(ldap_result_id, 0)if (result_data == []):breakelse:## here you don't have to append to a list## you could do whatever you want with the individual entry## The appending to list is just for illustration. if result_type == ldap.RES_SEARCH_ENTRY:result_set.append(result_data)print result_setexcept ldap.LDAPError, e:print e

Deleting an entry from an LDAP Server

Synchronous Delete
import ldap## first you must bind so we're doing a simple bind firsttry:l = ldap.open("127.0.0.1")l.protocol_version = ldap.VERSION3# Pass in a valid username and password to get # privileged directory access.# If you leave them as empty strings or pass an invalid value# you will still bind to the server but with limited privileges.username = "cn=Manager, o=anydomain.com"password  = "secret"# Any errors will throw an ldap.LDAPError exception # or related exception so you can ignore the resultl.simple_bind(username, password)except ldap.LDAPError, e:print e# handle error however you like# The next lines will also need to be changed to support your requirements and directorydeleteDN = "uid=anyuserid, ou=Customers,ou=Sales,o=anydomain.com"try:# you can safely ignore the results returned as an exception # will be raised if the delete doesn't work.l.delete_s(deleteDN)except ldap.LDAPError, e:print e## handle error however you like

 

 参考链接:

http://webservices.ctocio.com.cn/444/12159444.shtml

http://blog.csdn.net/sandayh/article/details/4525938

http://blog.csdn.net/sandayh/article/details/4525930

http://blog.sina.com.cn/s/blog_69ac00af01012e0g.html

http://hi.baidu.com/j60017268/item/e26222f9e56c0c1ae3e3bd28

http://www.ibm.com/developerworks/cn/aix/library/au-ldap_crud/

http://www.packtpub.com/article/installing-and-configuring-the-python-ldap-library-and-binding-to-an-ldap-directory