我正在使用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上的本地用户中没有此用户的条目。域用户将添加到本地安全组。
有什么想法吗?我希望能够提取此域用户所属的所有本地组的列表,然后查看该列表中是否存在某些组。现在唯一可行的选项是我搜索系统上的某些组,看看域用户是否属于该组。
答案 0 :(得分: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);
}
答案 1 :(得分:1)
我知道我的回答很晚,但这对我有用(在我尝试了各种排列之后):
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");