我知道有几个关于这个主题的讨论,但没有一个真正回答我的确切问题。 我正在寻找一种方法来远程检查当前登录的用户是否具有管理员权限。 他是本地内置的机器“管理员”组的成员还是“管理员”内嵌套组的成员,例如“域管理员”。 我找到了几种方法,但每种方法都只提供了一半的解决方案。
方法#1(远程工作但只检查本地“管理员”组):
private bool isAdmin()
{
ArrayList mem2 = new ArrayList();
string hostName = basicinfomodel.Loggedusername; //a username I get from another class
try
{
using (DirectoryEntry machine = new DirectoryEntry("WinNT://" + mycomputer.myComputerName)) // remote computer that I get from another class
{
//get local admin group
using (DirectoryEntry group = machine.Children.Find("Administrators", "Group"))
{
//get all members of local admin group
object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members)
{
//get account name
string accountName = new DirectoryEntry(member).Name;
mem2.Add(new DirectoryEntry(member).Name);
}
}
}
}
catch (Exception ex)
{
// catch
}
if (mem2.Contains(hostName.ToUpper()) || mem2.Contains(hostName.ToLower()))
return true;
else
return false;
}
方法#2(检查本地和域管理员权限,但不远程工作)
static bool isAdmin()
{
WindowsIdentity User = new WindowsIdentity(@"user01");
WindowsPrincipal princ = new WindowsPrincipal(User);
return princ.IsInRole(WindowsBuiltInRole.Administrator);
}
正如我所说,我没有找到任何方法来满足这两种需求。
- 检查用户是否真的拥有管理员权限
- 远程操作
感谢您的帮助!
最佳答案
好吧,我想我找到了一种方法,我正在分享以防其他人想要使用它。 我使用了我发现的几种方法并创建了以下方法(似乎有效)
static bool isAdmin(string username, string machinename)
{
using (PrincipalContext ctxMacine = new PrincipalContext(ContextType.Machine, machinename))
{
using (PrincipalContext ctxDomain = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(ctxDomain, IdentityType.SamAccountName, username);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctxMacine, "Administrators");
foreach (UserPrincipal usr in gp.GetMembers(true))
{
if (up != null)
{
if (up.SamAccountName.ToUpper() == usr.SamAccountName.ToUpper())
{
return true;
}
}
}
}
}
return false;
}
注意
这是一个天真的实现,您应该验证您的代码,检查 null
并处理异常。
关于C# 检查当前登录用户是否为管理员(远程机器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26298556/