Basic Environmentpython3.6 pip Install LDAP3
Code
#-*-Coding:utf-8-*-from ldap3 import Server, Connection, all, subtree, serverpool ldap_server_pool = [192.168.0.xx X "," 192.168.1.xxx "] ldap_server_port = 389 ADMIN_DN =" xxx@xxx.xxx "Admin_password =" xxxxxxx "Search_base =" ou=xxx,dc=x Xx,dc=xxx "def Ldap_auth" (Username, password): Ldap_server_pool = Serverpool (ldap_server_pool) conn = Connection ( Ldap_server_pool, USER=ADMIN_DN, Password=admin_password, Check_names=true, Lazy=false, RAISE_EXCEPTIONS=FALSE) conn . Open () conn.bind () res = Conn.search (search_base = search_base, Search_filter = ' (Samaccountna me={}) '. Format (username), Search_scope = subtree, attributes = [' cn ', ' givenname ', ' Mail ', ' sAMAccountName '], paged_size = 5) If res:entry = conn.response[0] DN = entry[' DN '] attr_dic t = entry[' attributes '] # Check password by dn try:conn2 = Connection (ldap_server_pool, user =DN, Password=password, chEck_names=true, Lazy=false, Raise_exceptions=false) conn2.bind () If conn2.result["description"] =
= "Success": Print (True, attr_dict["Mail", attr_dict["sAMAccountName"], attr_dict["givenname"))
Return (True, attr_dict["Mail"], attr_dict["sAMAccountName"], attr_dict["givenname") Else: Print ("auth fail") return (False, none, none, none) except Exception as E:prin T ("auth fail") return (false, none, none, none) Else:return (false, none, none, none) if __name __ = = "__main__": Ldap_auth ("Maqingxiong", "Mqx1801")