我正在尝试执行一个非常简单的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
答案 0 :(得分:2)
您的基本假设是错误的 - 计算机(或用户)不能在群组中暗示“遏制”群组内部;用户或计算机仅在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");
答案 1 :(得分:0)
当你说它不起作用时,你是说你找不到电脑?如果是这样,首先检查计算机是否在组中,有一个名为Active Directory exporer的好工具可以帮助您:http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx 如果它在组中,你可以尝试消除过滤器上计算机名称的过滤器并迭代结果集,以便找出你的元素是否存在:
ComputerSearch.Filter = ("(&(objectCategory=computer))";
SearchResult match = ComputerSearch.FindAll();
以下是有关如何查询AD的一些信息:http://www.codeproject.com/KB/system/everythingInAD.aspx