5

我正在使用 System.DirectoryServices.AccountManagement 命名空间来查找域用户及其相应的 AD 安全组。这很好用。

我还使用该命名空间来查询远程服务器上的本地安全组。我能够找到一个安全组,然后列出该组的用户没问题。

我遇到的问题是显示 DOMAIN 用户所属的 LOCAL 组:

PrincipalContext localmachine = new PrincipalContext(ContextType.Machine, "ServerName");
PrincipalContext domain = new PrincipalContext(ContextType.Domain);

// find the user using the domain context (Works fine)
UserPrincipal user = UserPrincipal.FindByIdentity(domain, userName);

// if found - grab its groups
if (user != null)
{
    // The get groups method is the only method that would accept a new context
    PrincipalSearchResult<Principal> groups = user.GetGroups(localMachine);

    // no groups are returned .... removed rest of code
}

我正在尝试使用传入 localMachine PrincipalContext 的 GetGroups 方法,但没有返回任何组。

用户仅存在于域 AD 中。localMachine 的本地用户中没有此用户的条目。域用户被添加到本地安全组。

有任何想法吗?我希望能够提取此域用户所属的所有本地组的列表,然后查看该列表中是否存在某个组。现在唯一可行的选择是搜索系统上的某些组,并查看域用户是否属于该组。

4

2 回答 2

3

以下代码将返回域用户所属的本地组:

        PrincipalContext domain = new PrincipalContext(ContextType.Domain);
        UserPrincipal user = UserPrincipal.FindByIdentity(domain, userName);
        foreach (GroupPrincipal group in user.GetAuthorizationGroups())
        {
            if (group.Context.ConnectedServer == serverName)
                Console.Out.WriteLine("{0}\\{1}", group.Context.Name, group.SamAccountName);
        }
于 2012-06-27T01:32:59.873 回答
3

我知道我的回答迟了,但这对我有用(在我尝试了各种排列之后):

private static IList<string> GetUserLocalGroups(string userAccountName, string computerName, string domainName)
{
  List<string> groups = new List<string>();

  // We have to deal with a local computer
  DirectoryEntry root = new DirectoryEntry(String.Format("WinNT://{0},Computer", computerName), null, null, AuthenticationTypes.Secure);


  foreach (DirectoryEntry groupDirectoryEntry in root.Children)
  {
    if (groupDirectoryEntry.SchemaClassName != "Group")
      continue;

    string groupName = groupDirectoryEntry.Name;
    Console.WriteLine("Checking: {0}", groupName);
    if (IsUserMemberOfGroup(groupDirectoryEntry, String.Format("WinNT://{0}/{1}", domainName, userAccountName)))
    {
      groups.Add(groupName);
    }
  }

  return groups;
}

private static bool IsUserMemberOfGroup(DirectoryEntry group, string userPath)
{
  return (bool)group.Invoke(
      "IsMember",
      new object[] { userPath }
      );
}

调用是这样的:

GetUserLocalGroups("samaccountname", "computerName.yourdomain", "yourdomain");
于 2013-12-12T02:21:58.190 回答