如何在AD中查找属于某个组的用户,并获取他们的SAMAccountName和SID?

时间:2011-12-02 03:19:20

标签: c# active-directory

我只是希望用户能够在文本框中输入组名,并只返回他们的登录名和他们的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();

2 个答案:

答案 0 :(得分:1)

包含SID的属性称为objectSid,对于NT4兼容版本和sAMAccountName,包含登录的属性为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]);
    }
  }
}

答案 1 :(得分:0)

我认为如果你颠倒你的查询会更好:

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

这样您就可以使用FindAll直接返回用户列表。不要忘记将sAMAccountName等添加到PropertiesToLoad