Thursday, January 19, 2012

Active Directory with IronPython

Here is a little snippet

import clr
clr.AddReference("System.DirectoryServices")
from System.DirectoryServices import DirectorySearcher

class ADHelper(object):

    def __init__(self, strLDAP = "LDAP://******"):
        self.searcher  =  DirectorySearcher(strLDAP)

    def searchUserByLogin(self,user,*prop):
        """        
        searchUserByLogin("alogin","cn","sn",'SAMAccountName')
        """        
        str = ""
        self.searcher.Filter = "(sAMAccountName=%s)"%user
        self.searcher.PropertiesToLoad.Add("cn")
        self.searcher.PropertiesToLoad.Add("SAMAccountName")
        self.searcher.PropertiesToLoad.Add("givenName")
        self.searcher.PropertiesToLoad.Add("sn")   
        result = self.searcher.FindOne()
        for option in prop:
            str +=  (option + " : " + result.Properties[option][0] + " ")
        return str
    
ad = ADHelper()
print ad.searchUserByLogin("alogin","cn","sn",'SAMAccountName')

No comments:

Post a Comment