使用本地 C# 应用程序检查 Windows 中的 MaxPasswordAge

Check MaxPasswordAge in Windows with local C# application

我试图在 Internet 上查找相关文档时遇到了最糟糕的情况。从本质上讲,我想知道 Secpol MaXPWAge 设置为 90 或更少,并将其显示在文本框中(为方便起见,我们将其称为 textbox1)我已经在审计员中搜索了 WMI 解决方案、注册表、GPEDIT,但没有找到任何结果。我确实找到了这个,但老实说,我不知道如何使用相同的代码来检查最大密码年龄而不是复杂性要求。拜托,有人可以告诉我我应该在这里做什么吗? C# 不是我的主要语言。

https://gist.github.com/jkingry/421802

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        Console.Write(PasswordComplexityPolicy());
    }

    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;
    }

    class IniFile
    {
        public static IniFile Load(string filename)
        {
            var result = new IniFile();
            result.Sections = new Dictionary<string, IniSection>();
            var section = new IniSection(String.Empty);
            result.Sections.Add(section.Name, section);

            foreach (var line in File.ReadAllLines(filename))
            {
                var trimedLine = line.Trim();
                switch (line[0])
                {
                    case ';':
                        continue;
                    case '[':
                        section = new IniSection(trimedLine.Substring(1, trimedLine.Length - 2));
                        result.Sections.Add(section.Name, section);
                        break;
                    default:
                        var parts = trimedLine.Split('=');
                        if(parts.Length > 1)
                        {
                            section.Add(parts[0].Trim(), parts[1].Trim());
                        }
                        break;
                }                    
            }

            return result;
        }

        public IDictionary<string, IniSection> Sections { get; private set; }
    }

    class IniSection : Dictionary<string, string>
    {
        public IniSection(string name) : base(StringComparer.OrdinalIgnoreCase)
        {
            this.Name = name;
        }

        public string Name { get; private set; }
    }
}

我会这样写 IniFile class:

class IniFile : Dictionary<string,Dictionary<string,string>> {
    public IniFile(string filename) {
        var currentSection = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        Add("", currentSection);
        foreach (var line in File.ReadAllLines(filename)) {
            var trimedLine = line.Trim();
            switch (line[0]) {
                case ';':
                    continue;
                case '[':
                    currentSection = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    Add(trimedLine.Substring(1, trimedLine.Length - 2), currentSection);
                    break;
                default:
                    var parts = trimedLine.Split('=');
                    if (parts.Length > 1) {
                        currentSection.Add(parts[0].Trim(), parts[1].Trim());
                    }
                    break;
            }
        }
    }
    public string this[string sectionName, string key] {
        get {
            Dictionary<string, string> section;
            if (!TryGetValue(sectionName, out section)) { return null; }
            string value;
            if (!section.TryGetValue(key, out value)) { return null; }
            return value;
        }
    }
    public int? GetInt(string sectionName, string key) {
        string stringValue = this[sectionName, key];
        int result;
        if (!int.TryParse(stringValue, out result)) { return null; }
        return result;
    }
}

并将ini文件生成放到单独的方法中:

class Program {
    static void GenerateSecEditOutput(out string tempFile) {
        tempFile = Path.GetTempFileName();
        var p = new Process {
            StartInfo = new ProcessStartInfo {
                FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\secedit.exe"),
                Arguments = String.Format(@"/export /cfg ""{0}"" /quiet", tempFile),
                CreateNoWindow = true,
                UseShellExecute = false
            }
        };
        p.Start();
        p.WaitForExit();
    }

    //... Main goes here
}

然后,Main 方法如下所示:

static void Main(string[] args) {
    //This will be the path of the temporary file which contains the output of secedit.exe
    string tempFile;

    //Write the output of secedit.exe to the temporary file
    GenerateSecEditOutput(out tempFile);

    //Parse the temporary file
    var iniFile = new IniFile(tempFile);

    //Read the maximum password age from the "System Access" section
    var maxPasswordAge = iniFile.GetInt("System Access", "MaximumPasswordAge");
    if (maxPasswordAge.HasValue) {
        Console.WriteLine("MaxPasswordAge = {0}", maxPasswordAge);
    } else {
        Console.WriteLine("Unable to find MaximumPasswordAge");
    }
    Console.ReadKey(true);
}

如果您有一些要将值放入的文本框,步骤大致相同。我们可以避免整数解析,并使用 IniFile:

的索引器
string tempFile;
GenerateSecEditOutput(out tempFile);
var iniFile = new IniFile(tempFile);
//assuming tb is a variable referring to a textbox
tb.Text = iniFile["System Access", "MaximumPasswordAge"];

请记住,secedit.exe 需要 运行 的管理员权限。没有管理员权限,代码不会失败;临时文件将只是空的。有关如何执行此操作的一些建议,请参阅 here

这有点像作弊,但如果您只寻找这一点,它就会起作用。基本上它会启动一个新进程和 运行s net accounts,然后从输出中转义 Maximum password age 字段。尝试一下,但您可能需要 运行 作为管理员:

var process = new Process
{
    StartInfo = new ProcessStartInfo()
    {
        FileName = "net",
        Arguments = "accounts",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

process.Start();
string text = "";
while (!process.StandardOutput.EndOfStream)
{
    text = process.StandardOutput.ReadLine();
    if (text != null && text.StartsWith("Maximum password age (days):"))
        break;
}
if (text == null || !text.StartsWith("Maximum password age (days):"))
    return;
text = text.Replace("Maximum password age (days):", "").Trim();

textBox1.Text = text;