如何从LDAP Active目录获取用户数据?

时间:2013-07-31 07:24:58

标签: django django-models ldap getjson

我是一个非常新的学习者,使用Active Directory来获取用户数据,但是获取数据很困难。我为此设置了所有环境。但是如何获取用户数据?请帮我 。我需要帐户信息,来自活动目录的组织数据

my views.py

def getLdapData(request):
try:
    l = ldap.initialize("ldap://192.100.78.45")
    username = "admin"
    password  = "Hxxxxxxx"
    l.simple_bind(username, password)  


except ldap.LDAPError, e:
    print e

searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = None 
baseDN = "dc=hashed,dc=local"
searchFilter = "dc=hashed,dc=local"


try:
    ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
    print "ldap_result_id : " ,  ldap_result_id  
    result_set = []
    i=1
    while 1:
        print i ," ",
        i=i+1
        result_type, result_data = l.result(ldap_result_id, 0)
        schema_entry=l.search_subschemasubentry_s(baseDN)

        m=l.get_option( ldap_result_id )

        print m
        if (result_data ==[]):
            break
        else:
            result_set.append(result_data)

except ldap.LDAPError, e:
    print" e---->"
    print e

return HttpResponse(content=simplejson.dumps({ 
            "schema_entry" : schema_entry,
          "LdapData" : result_set,  })     

JSON OUTPUT:

   LdapData: [
        [
          [
             null,
            [
           "ldap://ForestDnsZones.hashed.local/DC=ForestDnsZones,DC=hashed,DC=local"
            ]
          ]
        ],
        [
            [
             null,
               [
           "ldap://DomainDnsZones.hashed.local/DC=DomainDnsZones,DC=hashed,DC=local"
               ]
            ]
        ],
      [
           [
               null,
                [
                 "ldap://hashed.local/CN=Configuration,DC=hashed,DC=local"
                ]
           ]
     ]
   ],
    schema_entry: "CN=Aggregate,CN=Schema,CN=Configuration,DC=hashed,DC=local"
   }

1 个答案:

答案 0 :(得分:0)

我得到了解决方案: - 我已经更改了我的过滤器变量,它开始工作.. :))

这是我使用的课程和方法:

class LdapDataReciver:
def get_access_token(self,data):
    user_detail = {'user_name':data}
    auth = HMAAuthentication(expire_duration=4*60*60)
    access_token = auth.create_access_token(user_detail)
    return access_token

def get_group(self,list):
    groups=[]
    try:
        for entry in list:
            cn = entry.split(' ')
            cn1 = cn[0].split('=')
            groups.append(cn1[1])
        return groups; 
    except :
        raise AuthenticationException("userName does not exist")    


def authenticate_with_active_directory(self,username,password):
    try:
        l = ldap.initialize(settings.LDAP_URL)
        l.simple_bind(username, password) 
    except ldap.LDAPError as e:
        raise AuthenticationException("""Could not bind username %s and password
         to ldap url %s, got exception %s""" % (username, settings.LDAP_URL, str(e))) 

    match = re.search(r'@', username)
    if match:   
        user_id=username.split("@")                    
    else:
        user_id=username
    search_scope = ldap.SCOPE_SUBTREE
    base_dn =settings.BASE_DN
    filter = "(&(objectClass=user)(sAMAccountName=%s))" % user_id[0]
    try:
        ldap_result_id = l.search(base_dn, search_scope, filter, None)
        result_type, result_data = l.result(ldap_result_id, all=0) 

        ldap_data=result_data[0][1]            
        data_set={};   
        if ldap_data: 
            firstName=ldap_data['name'][0] 
            data_set["memberOf"] =ldap_data['memberOf']
            data_set["displayName"]=ldap_data['displayName'][0]
            data_set["firstName"]=ldap_data['givenName'][0]
            data_set["sAMAccountName"]=ldap_data['sAMAccountName'][0]
            data_set["email"]=ldap_data['mail'][0]
            data_set["access_token"]=self.get_access_token(firstName[0])
            data_set["department"]=ldap_data['department'][0]
            data_set["lastName"]=ldap_data['sn'][0]
            data_set["goups"]= self.get_group(data_set["memberOf"])
            data_set["middleName"]=ldap_data['initials'][0]

        return data_set

    except ldap.LDAPError, e:
        raise AuthenticationException("""got exception %s""" % (  str(e)))