Python实现LDAP用户名密码认证
1 Python实现LDAP用户名密码认证,来实现统一认证
-
#!/usr/bin/python
-
-
import ldap
-
-
# ldap server's ip address.
-
# the ldap server default port is 389, if your ldap server is use SSL port 636,
-
# pls. change to : ldap://192.168.13.13:636
-
ldap_path = "ldap://192.168.13.13"
-
# ladp administrator, use to find the input user is exist in ldap.
-
ldap_user = "Manager"
-
# ldap administrator password.
-
ldap_pwd = "secret"
-
# ldap base.
-
base_dn = "dc=maxcrc,dc=com"
-
-
# get the dn of user
-
def validateLDAPUser(user):
-
try:
-
conn = ldap.initialize(ldap_path)
-
# the ldap default version is version3,
-
#if your ldap server is use ldap version1, or version2,
-
# pls. change this to VERSION1 VERSION2
-
conn.protocol_version = ldap.VERSION3
-
conn.simple_bind(ldap_user, ldap_pwd)
-
-
searchScope = ldap.SCOPE_SUBTREE
-
searchFiltername = "uid"
-
retrieveAttributes = None
-
-
# ensure the user is exist in ldap
-
searchFilter = '(' + searchFiltername + "=" + user + ')'
-
ldap_result_id = conn.search(base_dn, searchScope, searchFilter, retrieveAttributes)
-
result_type, result_data = conn.result(ldap_result_id, 1)
-
if (not len(result_data) == 0):
-
return 1, result_data[0][0]
-
else:
-
return 0, ''
-
-
except ldap.LDAPError, e:
-
print e
-
return 0, ''
-
-
finally:
-
conn.unbind()
-
del conn
-
-
#if time out, retry
-
def get_dn(user, try_num=2):
-
i = 0
-
is_found = 0
-
found_result = ""
-
while (i < try_num):
-
is_found, found_result = validateLDAPUser(user)
-
if (is_found):
-
break
-
i += 1
-
return found_result
-
-
# test the username is exist in ldap server, and it's password is correct.
-
def LDAPLogin(user_name, user_pwd):
-
try:
-
if (user_name == ""):
-
print "Username is empty!"
-
return
-
if (user_pwd == ""):
-
print "Password is empty!"
-
return
-
-
dn = get_dn(user_name, 2)
-
if (dn == ''):
-
print "User Not Exist"
-
return
-
else:
-
print "User Name Ok"
-
ldap_conn = ldap.initialize(ldap_path)
-
ldap_conn.simple_bind_s(dn, user_pwd)
-
print "Login Success!"
-
except Exception, e:
-
print "Login Failed!"
-
-
finally:
-
ldap_conn.unbind()
-
del ldap_conn
-
-
-
# param 1: in, the ldap user name, such as san.zhang
-
# param 2: in, the password of input user.
-
# other: pls. add a return value based on your need.
-
LDAPLogin("zhiye.wang", "123456")
阅读(3524) | 评论(0) | 转发(0) |