AD用户登录验证,遍历OU(LDAP)
先安装python-ldap模块
1.验证AD用户登录是否成功
import sqlite3,ldap domainname='cmr\\' username='zhangsan' ldapuser = domainname + username ldappass='password' ldappath='ldap://192.168.200.20:389/' baseDN='OU=ouname,DC=d1,DC=d2,DC=com' l=ldap.initialize(ldappath) l.protocol_version = ldap.VERSION3 try: l.simple_bind_s(ldapuser,ldappass) #print l.simple_bind_s(ldapuser,ldappass) except Exception,err: #ldap.LDAPError print err.message['desc'] #DC无法连通,或凭据错误,报错也不同
2.验证用户queryusername是否存在
import ldap domainname='dname\\' username='authname' queryusername ='queryusername' ldapuser = domainname + username ldappass='password' ldappath='ldap://192.168.200.20:389/' baseDN='OU=拍,DC=d1,DC=d2,DC=com' try: l = ldap.initialize(ldappath) l.protocol_version = ldap.VERSION3 #l.simple_bind(ldapuser,ldappass) l.bind_s(ldapuser,ldappass) searchScope = ldap.SCOPE_SUBTREE searchFiltername = "sAMAccountName" #通过samaccountname查找用户 retrieveAttributes = None searchFilter = '(' + searchFiltername + "=" + queryusername +')' #searchFilter = '(' + searchFiltername + "=" + username +'*)' 加星号表示模糊查找 ldap_result =l.search_s(baseDN, searchScope, searchFilter, retrieveAttributes) #返回结果为list或None #searchFilter = '(&(objectClass=person)(sAMAccountName=username))' #ldap_result =l.search(baseDN, searchScope, searchFilter, retrieveAttributes) #ldap_result =l.search_ext_s(baseDN, searchScope, searchFilter, retrieveAttributes) #print ldap_result if len(ldap_result) == 0: print queryusername + ' Doesnot Exist' except ldap.LDAPError, e: print e finally: l.unbind_s() #解除ldap binding del l
3.遍历某个OU下所有用户
# -*- coding: UTF-8 -*- import ldap domainname='umr\\' username='authusername' ldapuser = domainname + username ldappass='password' ldappath='ldap://192.168.200.20:389/' baseDN='OU=ServerAdmin,DC=umr,DC=uu,DC=com' try: l = ldap.initialize(ldappath) l.protocol_version = ldap.VERSION3 #l.simple_bind(ldapuser,ldappass) l.bind_s(ldapuser,ldappass) searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = None searchFilter = '(&(objectClass=person))' #遍历该OU下所有用户,包含子OU ldap_result =l.search_s(baseDN, searchScope, searchFilter, retrieveAttributes) #返回结果为list或None for pinfor in ldap_result: #pinfor是一个tuple,第一个元素是该用户的CN,第二个元素是一个dict,包含有用户的所有属性 if pinfor[1]: p=pinfor[1] sAMAccountName = p['sAMAccountName'][0] #返回值是一个list displayName = p['displayName'][0] #如果用户的某个属性为空,则dict中不会包含有相应的key if 'department' in p: department = p['department'][0] else: department = None print sAMAccountName,displayName,department if len(ldap_result) == 0: print queryusername + ' Doesnot Exist' except ldap.LDAPError, e: print e finally: l.unbind_s() #解除ldap binding del l
参考:http://blog.sina.com.cn/s/blog_69ac00af01012e0g.html
http://www.vpsee.com/2012/11/use-python-ldap-to-create-read-delete-upgrade-ldap-entries/
https://www.python-ldap.org/doc/html/ldap.html#ldap.LDAPObject.search