# -*- coding: UTF-8 -*-
#
# python ldap doc
# http://www.python-ldap.org/en/latest/reference/ldap.html
#
import ldap, json
def ldap_login(ldap_path, user, domain, passwd):
try:
c = ldap.initialize(ldap_path)
c.protocol_version = ldap.VERSION3
d = c.simple_bind("%s@%s"%(user, domain), passwd)
except ldap.INVALID_CREDENTIALS, e:
c.unbind()
c = d = None
finally:
return c, d
def user_info(c, user, base):
try:
scope = ldap.SCOPE_SUBTREE
filterstr = "(sAMAccountName=%s)"%user
id = c.search(base, scope, filterstr, None)
result_type, result_data = c.result(id, 1)
return result_data
except ldap.LDAPError, e:
return None
finally:
pass
####
ldap_path = "ldap://192.168.22.129:389"
base = "DC=dev,DC=com"
user = "test"
domain = "dev.com";
passwd = "1qaz@WSX";
c, d = ldap_login(ldap_path, user, domain, passwd)
if c == None:
print "login error!"
exit(1)
print "user: %s login ok!"%user
info = user_info(c, user, base)
print json.dumps(info, ensure_ascii=False, indent=4)
c.unbind()
程序返回结果
user: test login ok!
[
[
"CN=test,CN=Users,DC=dev,DC=com",
{
"primaryGroupID": [
"513"
],
"logonCount": [
"2"
],
"cn": [
"test"
],
"countryCode": [
"0"
],
"objectClass": [
"top",
"person",
"organizationalPerson",
"user"
],
"userPrincipalName": [
"test@dev.com"
],
"adminCount": [
"1"
],
"lastLogonTimestamp": [
"131911416435300980"
],
"instanceType": [
"4"
],
"distinguishedName": [
"CN=test,CN=Users,DC=dev,DC=com"
],
"dSCorePropagationData": [
"20190105065609.0Z",
"16010101000000.0Z"
],
"objectSid": [
"\u0001\u0005\u0000\u0000\u0000\u0000\u0000\u0005\u0015\u0000\u0000\u00000\u0004\u0000\u0000"
],
"whenCreated": [
"20190105055908.0Z"
],
"uSNCreated": [
"12765"
],
"badPasswordTime": [
"0"
],
"pwdLastSet": [
"131911415491078266"
],
"sAMAccountName": [
"test"
],
"objectCategory": [
"CN=Person,CN=Schema,CN=Configuration,DC=dev,DC=com"
],
"lastLogon": [
"131911419521867631"
],
"objectGUID": [
"g002+"
],
"whenChanged": [
"20190105065609.0Z"
],
"badPwdCount": [
"0"
],
"accountExpires": [
"9223372036854775807"
],
"displayName": [
"test"
],
"name": [
"test"
],
"memberOf": [
"CN=Administrators,CN=Builtin,DC=dev,DC=com"
],
"codePage": [
"0"
],
"userAccountControl": [
"66048"
],
"sAMAccountType": [
"805306368"
],
"uSNChanged": [
"12788"
],
"sn": [
"test"
],
"lastLogoff": [
"0"
]
}
],
[
null,
[
"ldap://ForestDnsZones.dev.com/DC=ForestDnsZones,DC=dev,DC=com"
]
],
[
null,
[
"ldap://DomainDnsZones.dev.com/DC=DomainDnsZones,DC=dev,DC=com"
]
],
[
null,
[
"ldap://dev.com/CN=Configuration,DC=dev,DC=com"
]
]
]