#!/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...python