using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
class AccountLockoutPolicySetter
{
const int TARGET_THRESHOLD = 5;
const int TARGET_DURATION = 30;
const int TARGET_RESET = 30;
static void Main()
{
// 先檢查當(dāng)前策略
if (CheckCurrentPolicy())
{
Console.WriteLine("當(dāng)前策略已符合要求,無(wú)需修改");
return;
}
// 策略配置代碼(原邏輯)
ApplyNewPolicy();
}
static bool CheckCurrentPolicy()
{
string exportPath = Path.Combine(Path.GetTempPath(), "current_policy.inf");
try
{
// 導(dǎo)出當(dāng)前策略
ProcessStartInfo exportInfo = new ProcessStartInfo
{
FileName = "secedit",
Arguments = $"/export /cfg \"{exportPath}\"",
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = true,
Verb = "runas" // 需要管理員權(quán)限
};
using (Process exportProc = Process.Start(exportInfo))
{
exportProc.WaitForExit();
if (exportProc.ExitCode != 0) return false;
}
// 解析策略文件
var lines = File.ReadAllLines(exportPath);
bool inSystemAccess = false;
int currentThreshold = 0;
int currentDuration = 0;
int currentReset = 0;
foreach (string line in lines)
{
string cleanLine = line.Split(';')[0].Trim(); // 移除注釋
if (cleanLine.StartsWith("[System Access]"))
{
inSystemAccess = true;
continue;
}
else if (cleanLine.StartsWith("["))
{
inSystemAccess = false;
continue;
}
if (inSystemAccess && cleanLine.Contains("="))
{
string[] parts = cleanLine.Split('=');
string key = parts[0].Trim();
string value = parts[1].Trim();
switch (key)
{
case "LockoutBadCount":
int.TryParse(value, out currentThreshold);
break;
case "LockoutDuration":
int.TryParse(value, out currentDuration);
break;
case "ResetLockoutCount":
int.TryParse(value, out currentReset);
break;
}
}
}
// 策略比對(duì)
return currentThreshold == TARGET_THRESHOLD &&
currentDuration == TARGET_DURATION &&
currentReset == TARGET_RESET;
}
catch
{
return false;
}
finally
{
if (File.Exists(exportPath)) File.Delete(exportPath);
}
}
static void ApplyNewPolicy()
{
string infContent = $@"
[Unicode]
Unicode=yes
[Version]
signature=""$CHICAGO$""
Revision=1
[System Access]
LockoutBadCount = {TARGET_THRESHOLD}
ResetLockoutCount = {TARGET_RESET}
LockoutDuration = {TARGET_DURATION}";
string tempInfPath = Path.Combine(Path.GetTempPath(), "lockoutpolicy.inf");
try
{
File.WriteAllText(tempInfPath, infContent);
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "secedit",
Arguments = $"/configure /db secedit.sdb /cfg \"{tempInfPath}\"",
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "runas",
UseShellExecute = true
};
using (Process proc = Process.Start(startInfo))
{
proc.WaitForExit();
Console.WriteLine(proc.ExitCode == 0
? "策略已成功更新!"
: $"更新失敗,錯(cuò)誤碼: {proc.ExitCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"操作異常: {ex.Message}");
}
finally
{
if (File.Exists(tempInfPath)) File.Delete(tempInfPath);
}
}
}?