Sag*_*b.g 4 c# windows privileges
我知道有几个关于这个主题的讨论,但没有一个真正回答我的确切问题.我正在寻找一种方法,如果当前登录的用户具有管理员权限,将远程检查.他是否是本地内置"管理员"组的成员或"管理员"内嵌套组的成员,例如"域管理员".我发现了几种方法,但每种方法只提供一半解决方案.
方法#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;
}
Run Code Online (Sandbox Code Playgroud)
方法#2(检查本地和域管理员权限,但不能远程工作)
static bool isAdmin()
{
WindowsIdentity User = new WindowsIdentity(@"user01");
WindowsPrincipal princ = new WindowsPrincipal(User);
return princ.IsInRole(WindowsBuiltInRole.Administrator);
}
Run Code Online (Sandbox Code Playgroud)
所以我说,我没有找到任何能满足这两种需求的方法.
谢谢您的帮助!
好吧,我想我找到了一种方法来做到这一点,我分享以防其他人想要使用它.我玩了几个我发现的方法,并创建了以下(似乎工作)
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;
}
Run Code Online (Sandbox Code Playgroud)
注意
这是一个简单的实现,您应该验证您的代码,检查null和处理异常.