2011-12-02 18 views
2

我只想讓用戶能夠在文本框中輸入組名,並返回他們的登錄名和他們的SID。如何查找AD中屬於某個組的用戶,並獲取他們的SAMAccountName和SID?

到目前爲止,我有這個,並加載組中的用戶,但我不確定如何提取登錄和SID。

SearchResult result; 
      DirectorySearcher search = new DirectorySearcher(); 
      search.Filter = String.Format("(cn={0})", txtGroup.Text); 
      search.PropertiesToLoad.Add("member"); 
      search.PropertiesToLoad.Add("cn"); 
      search.PropertiesToLoad.Add("objectGUID"); 
      result = search.FindOne(); 


      StringBuilder userNames = new StringBuilder(); 
      if (result != null) 
      { 
       for (int counter = 0; counter < 
       result.Properties["member"].Count; counter++) 
       { 
        string user = (string)result.Properties["member"][counter]; 
        userNames.AppendLine(user); 

       } 
      } 
      lblResults.Text = userNames.ToString(); 

回答

0

我認爲這將更好地工作,如果你反向查詢:

(&(objectClass=user)(memberOf={0})) 

這樣,那麼你可以直接使用FindAll找回用戶的列表。不要忘記將sAMAccountName等添加到PropertiesToLoad

1

包含SID的屬性名爲objectSid,其中包含登錄的屬性爲sAMAccountName,對於NT4兼容版本和userPrincipalName。你最好使用@Virkkunen的建議。

static void Main(string[] args) 
{ 
    /* Connection to Active Directory 
    */ 
    DirectoryEntry deBase = new DirectoryEntry("LDAP://192.168.183.138:389/dc=societe,dc=fr", "administrateur", "pwd"); 

    /* Directory Search 
    */ 
    DirectorySearcher dsLookForGrp = new DirectorySearcher(deBase); 
    dsLookForGrp.Filter = String.Format("(cn={0})", "yourgroup"); 
    dsLookForGrp.SearchScope = SearchScope.Subtree; 
    dsLookForGrp.PropertiesToLoad.Add("distinguishedName"); 
    SearchResult srcGrp = dsLookForGrp.FindOne(); 

    /* Directory Search 
    */ 
    DirectorySearcher dsLookForUsers = new DirectorySearcher(deBase); 
    dsLookForUsers.Filter = String.Format("(&(objectCategory=person)(memberOf={0}))", srcGrp.Properties["distinguishedName"][0]); 
    dsLookForUsers.SearchScope = SearchScope.Subtree; 
    dsLookForUsers.PropertiesToLoad.Add("objectSid"); 
    dsLookForUsers.PropertiesToLoad.Add("userPrincipalName "); 
    dsLookForUsers.PropertiesToLoad.Add("sAMAccountName"); 
    SearchResultCollection srcLstUsers = dsLookForUsers.FindAll(); 

    foreach (SearchResult sruser in srcLstUsers) 
    { 
    Console.WriteLine("{0}", sruser.Path); 

    SecurityIdentifier sid = new SecurityIdentifier((byte[]) sruser.Properties["objectSid"][0], 0); 
    Console.WriteLine(sid.ToString());  

    foreach (string property in sruser.Properties.PropertyNames) 
    { 
     Console.WriteLine("\t{0} : {1} ", property, sruser.Properties[property][0]); 
    } 
    } 
} 
相關問題