簡體   English   中英

Active Directory - 查找組中的計算機

[英]Active Directory - Find a computer in a group

我正在嘗試做一個非常簡單的AD查詢,以查看計算機是否在組中。 以下代碼看起來足夠直觀,但不起作用。 LDAPString是NetBIOSName引用的計算機是memberOf的組的完全區分名稱。

public bool IsComputerInADGroup(String LDAPString, String NetBIOSName)
{
    using (DirectoryEntry entry = new DirectoryEntry(String.Format(@"LDAP://{0}", LDAPString)))
    using (DirectorySearcher computerSearch = new DirectorySearcher(entry))
    {
        ComputerSearch.Filter = String.Format("(&(objectCategory=computer)(CN={0}))", NetBIOSName);
        SearchResult match = ComputerSearch.FindOne();

        if (match != null)
        {
            return true;
        }
    }

    return false;
}

有人可以解釋為什么這是不正確的,以及執行此搜索的正確/最快方法是什么。

謝謝P

您的基本假設是錯誤的-一台計算機(或用戶)不能在一個小組中,這暗示着小組內的“包容”; 用戶或計算機僅在OU內部。

用戶或計算機可以是任意數量的組的成員 - 但您需要針對組的成員屬性(或作為該組成員的元素的memberOf屬性)進行檢查。

所以最簡單的方法就是

  • 綁定到有問題的對象
  • 刷新其屬性緩存以獲取memberOf的最新條目
  • 枚舉其memberOf條目,並查看您要查找的組是否存在

就像是:

 public static bool IsAccountMemberOfGroup(string account, string group)
 {
    bool found = false;

    using (DirectoryEntry entry = new DirectoryEntry(account))
    {
        entry.RefreshCache(new string[] { "memberOf" });

        foreach (string memberOf in entry.Properties["memberOf"])
        {
           if (string.Compare(memberOf, group, true) == 0)
           {
              found = true;
              break;
           }
        }
    }

    return found;
 }

這樣稱呼:

bool isMemberOf = 
     IsAccountMemberOfGroup("LDAP://cn=YourComputer,dc=Corp,dc=com",
                            "CN=yourGroupInQuestion,OU=SomeOU,dc=corp,dc=com");

你應該沒事

更新:如果您使用的是.NET 3.5,您還可以使用新的System.DirectoryServices.AccountManagement命名空間和LINQ來簡化操作:

public static bool IsAccountMemberOfGroup2(PrincipalContext ctx, string account, string groupName)
{
   bool found = false; 
   GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);

   if (group != null)
   {
      found = group.GetMembers()
                 .Any(m => string.Compare(m.DistinguishedName, account, true) == 0);
   }

   return found;
}

並稱之為:

// establish default domain context    
PrincipalContext domain = new PrincipalContext(ContextType.Domain);

// call your function
bool isMemberOf = 
   IsAccountMemberOfGroup2(domain, 
                           "cn=YourComputer,dc=Corp,dc=com",
                           "CN=yourGroupInQuestion,OU=SomeOU,dc=corp,dc=com");

當你說它不起作用時,你是說你找不到電腦? 如果是這樣,請首先檢查計算機是否在組中,那里有一個不錯的工具,名為Active Directory Exporer,它可以為您提供幫助: http ://technet.microsoft.com/zh-cn/sysinternals/bb963907.aspx在該組中,您可以嘗試為過濾器上的計算機名消除過濾器,並遍歷結果集以找出您的元素是否存在:

ComputerSearch.Filter = ("(&(objectCategory=computer))";
    SearchResult match = ComputerSearch.FindAll();

以下是有關如何查詢AD的一些信息: http//www.codeproject.com/KB/system/everythingInAD.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM