我知道有几个关于这个主题的讨论,但没有一个真正回答我的确切问题。我正在寻找一种方法,如果当前登录的用户具有管理员权限,将远程检查。他是否是本地内置“管理员”组的成员或“管理员”内部嵌套组的成员,例如“域管理员”。我发现了几种方法,但每种方法只提供一半解决方案。
方法#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
并处理异常。
上面的解决方案是好的,但它可以为不同的情况抛出太多的异常,你必须在该远程机器上管理员运行此方法毫无例外。
所以..我不想捕捉所有可能的异常,我想尽快做到这一点。
所以对我来说,这是对远程机器上当前用户管理权限的最佳和最快速的检查:
public static bool AdminCheck(string machineName)
{
if (Directory.Exists(string.Format("\\\\{0}\\admin$", machineName)))
{
return true;
}
return false;
}
没有管理员权限,您无法访问管理共享,并且当有人删除它们时,它们会自动重新创建。说实话..我不认为有人会尝试删除操作系统文件夹。
您可以在这里找到所有更接近的信息:https://en.wikipedia.org/wiki/Administrative_share