Saturday 16 November 2013

How to setup active directory LDAP in Python

For setup active directory we need LDAP connection . Using ldap connection we can connect active directory and we can find all users and computers which is connected through it.


The Lightweight Directory Access Protocol (LDAP) is an application protocol for accessing and maintaining distributed directory information services over an Internet Protocol (IP) network.
Directory services may provide any organized set of records, often with a hierarchical structure, such as a corporate email directory. Similarly, a telephone directory is a list of subscribers with an address and a phone number.

Active directory is nothing but a server where many system can connect and we can create number of users. So in 1 system number of users can work with active directory.

Here we will connect Active directory through ldap connection.


try:
    l = ldap.initialize("ldap://example.com")
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
    bind = l.simple_bind_s("administrator@example.com", "example@123")
    print "Connected is establised!"
except:
    print "Connected failed!"

Above code  is for connection establishment
Now how to find user's list
try:
    l = ldap.initialize("ldap://example.com")
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
    bind = l.simple_bind_s("administrator@example.com", "example@123")
    print "Connected is establised!"
    base = "dc=example, dc=com"
    criteria = "(&(objectClass=user)(cn=*))"
    #attributes = ['cn','dNSHostName','sAMAccountName','name']
    attributes = ['name']
    result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria,  attributes)
    results = [entry for dn, entry in result if isinstance(entry, dict)]
    print results
except:
    print "Connected failed!"
 
  
How to find computers list
try:
    l = ldap.initialize("ldap://example.com")
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
    bind = l.simple_bind_s("administrator@example.com", "example@123")
    print "Connected is establised!"
    base = "dc=example, dc=com"
    criteria = "(&(objectClass=computer)(cn=*))"
    #attributes = ['cn','dNSHostName','sAMAccountName','name']
    attributes = ['name']
    result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria,  attributes)
    results = [entry for dn, entry in result if isinstance(entry, dict)]
    print results
except:
    print "Connected failed!"
 
 
Before run this code you have to download ldap module Download LDAP

No comments:

Post a Comment