使用python模拟Simple方式连接ldap

418 查看

#!/usr/bin/python
# -*- coding: utf-8 -*-
# filename: ldap_test.py
import ldap

'''
实现LDAP用户登录验证,首先获取用户的dn,然后再验证用户名和密码
'''

#获得用户的dn
def getLdapUserDN(user):
    l = ldap.initialize(ldapPath)
    # Set LDAP protocol version used
    l.protocol_version = ldap.VERSION3
    l.simple_bind_s(ldapUser,ldapPasswd)
    # l.simple_bind_s(dn,ldapPasswd) 

    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):
        r_a,r_b = result_data[0]
        print r_b["distinguishedName"]
        return 1, r_b["distinguishedName"][0]
    else:
        return 0, ''
        

if __name__ == '__main__':
    ldapPath = "ldap://x.x.x.x"
    baseDN = "OU=demo,DC=AD,DC=xx,DC=com"
    # ldapUser = "root"
    ldapUser = "CN=admin,OU=demo,DC=AD,DC=xx,DC=com"
    ldapPasswd = "demo"
    passwd = "0"
    dn = getLdapUserDN("test1")[1]
    print dn
    my_ldap = ldap.initialize(ldapPath)
    print my_ldap.simple_bind_s(dn,passwd)

参考文档:
http://www.vpsee.com/2012/11/use-python-...
http://www.linuxidc.com/Linux/2015-02/11...