读取本地组策略/ Active Directory设置

我正在编写一个C#程序,它将根据Windows组策略设置“密码必须满足复杂性要求”强制执行密码复杂性。 具体来说,如果该策略在本地计算机(如果它不是域的一部分)或域安全策略(对于域成员)上设置为“已启用”,则我的软件需要为其自身的内部安全性强制执行复杂的密码。

问题是我无法弄清楚如何阅读该GPO设置。 Google搜索表明我可以使用以下两种API中的一种来读取GPO设置:.NET Framework中的System.DirectoryServices库和Windows Management Instrumentation(WMI),但到目前为止我还没有取得任何成功。

任何见解都会有所帮助。

似乎没有针对此任务,托管或其他方式的文档化API。

管理尝试

我使用System.Management程序集尝试了托管路由:

ConnectionOptions options = new ConnectionOptions(); ManagementScope scope = new ManagementScope(@"\\.\root\RSOP\Computer", options); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery("SELECT * FROM RSOP_SecuritySettingBoolean")); foreach(ManagementObject o in searcher.Get()) { Console.WriteLine("Key Name: {0}", o["KeyName"]); Console.WriteLine("Precedence: {0}", o["Precedence"]); Console.WriteLine("Setting: {0}", o["Setting"]); } 

然而,这不会返回结果。 它似乎不是一个权限问题,因为向ConnectionOptions提供用户名/密码对会导致exception,告诉您在本地连接时无法指定用户名。

不受管理的尝试

我看了一下NetUserModalsGet 。 虽然这将返回有关密码设置的一些信息:

 typedef struct _USER_MODALS_INFO_0 { DWORD usrmod0_min_passwd_len; DWORD usrmod0_max_passwd_age; DWORD usrmod0_min_passwd_age; DWORD usrmod0_force_logoff; DWORD usrmod0_password_hist_len; } USER_MODALS_INFO_0, *PUSER_MODALS_INFO_0, *LPUSER_MODALS_INFO_0; 

..it不会告诉我是否启用了密码复杂性策略。

工具输出刮痧“成功”

所以我使用解析secedit.exe输出。

  public static bool PasswordComplexityPolicy() { var tempFile = Path.GetTempFileName(); Process p = new Process(); p.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\secedit.exe"); p.StartInfo.Arguments = String.Format(@"/export /cfg ""{0}"" /quiet", tempFile); p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.Start(); p.WaitForExit(); var file = IniFile.Load(tempFile); IniSection systemAccess = null; var passwordComplexityString = ""; var passwordComplexity = 0; return file.Sections.TryGetValue("System Access", out systemAccess) && systemAccess.TryGetValue("PasswordComplexity", out passwordComplexityString) && Int32.TryParse(passwordComplexityString, out passwordComplexity) && passwordComplexity == 1; } 

完整代码: http : //gist.github.com/421802

您可以使用策略的结果集(RSOP)工具。 例如,这是一个VBScript(从这里取消),它将告诉你你需要知道什么。 它应该很简单,将其转换为C#。

 strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\rsop\computer") Set colItems = objWMIService.ExecQuery _ ("Select * from RSOP_SecuritySettingBoolean") For Each objItem in colItems Wscript.Echo "Key Name: " & objItem.KeyName Wscript.Echo "Precedence: " & objItem.Precedence Wscript.Echo "Setting: " & objItem.Setting Wscript.Echo Next 

我遇到了你的这个微软论坛答案http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/f3f5a61f-2ab9-459e-a1ee-c187465198e0

希望这有助于将来遇到这个问题的人。