C# 使用UserPrincipal检查本地管理员
我正在尝试使用一个方法,该方法接收用户名,如果该用户是本地管理员(不在整个域上,只在本地计算机上),则返回true,否则返回false。我试图改变在工作中发现的技术,但没有成功。我尝试过使用NetUserGetInfo方式,但无法实现。现在我尝试使用UserPrincipal。下面的代码是我所有的…主要是测试基本的工作,他们做C# 使用UserPrincipal检查本地管理员,c#,active-directory,admin,active-directory-group,userprincipal,C#,Active Directory,Admin,Active Directory Group,Userprincipal,我正在尝试使用一个方法,该方法接收用户名,如果该用户是本地管理员(不在整个域上,只在本地计算机上),则返回true,否则返回false。我试图改变在工作中发现的技术,但没有成功。我尝试过使用NetUserGetInfo方式,但无法实现。现在我尝试使用UserPrincipal。下面的代码是我所有的…主要是测试基本的工作,他们做 PrincipalContext ctx = new PrincipalContext(ContextType.Machine); UserPrincipal usr =
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId);
if(usr == null)
{
Console.WriteLine("usr is null");
}
else
{
Console.WriteLine(usr.Enabled);
Console.WriteLine(usr.IsAccountLockedOut());
foreach (Principal p in usr.GetAuthorizationGroups())
{
Console.WriteLine(p.ToString());
}
}
看起来我应该能够使用isMemberOf方法,但是如何为本地管理员创建一个组呢?或者有比isMemberOf方法更好的方法吗?实际上,我可以检查从GetAuthorizationGroups()返回的主体之一是否等于“Administrators”
另一种可能性。如果从UserPrincipal对象获取WindowsIdentity。您可以使用IsInRole(groupname)方法 您可以通过执行以下操作获取WindowsIdentity
var identity = new WindowsIdentity(string sUserPrincipalName);
// then use this method to check the Identity against any Active Directory group.
public static bool UserIsInRole(WindowsIdentity identity, string group)
{
try
{
return new WindowsPrincipal(identity).IsInRole(group);
}
catch (Exception ex)
{
//Error checking role membership
return false;
}
}
这个就行了
static bool IsAdmin()
{
// net localgroup administrators
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "net",
Arguments = "localgroup administrators",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
var computer = new PrincipalContext(ContextType.Machine).ConnectedServer;
var isAdmin = proc.StandardOutput.ReadToEnd().Contains(computer);
return isAdmin;
}
static bool IsAdmin()
{
// net localgroup administrators
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "net",
Arguments = "localgroup administrators",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
var computer = new PrincipalContext(ContextType.Machine).ConnectedServer;
var isAdmin = proc.StandardOutput.ReadToEnd().Contains(computer);
return isAdmin;
}