資安相關 – 檢查ad 帳號密碼180天到期

因為資安規定,公司網域密碼需180天更新一次。用c#檢查

Console.Write("請輸入域名: ");
string domain = Console.ReadLine();

Console.Write("請輸入有權限查詢 AD 的用戶名: ");
string username = Console.ReadLine();

Console.Write("請輸入密碼: ");
string password = Console.ReadLine();
try
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, username, password))
{
if (!context.ValidateCredentials(username, password))
{
throw new Exception("提供的憑證無效。請檢查用戶名和密碼。");
}

UserPrincipal userPrincipal = new UserPrincipal(context);
PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal);

Console.WriteLine("\n用戶帳號\t\t用戶名稱\t\t最後密碼更新日期\t預計密碼到期日期");
Console.WriteLine("--------------------------------------------------------------------------------");

foreach (UserPrincipal user in searcher.FindAll().Cast())
{
DateTime? lastPasswordSet = user.LastPasswordSet;
DateTime? estimatedPasswordExpiry = lastPasswordSet?.AddDays(180);
Console.WriteLine($"{user.SamAccountName,-20}" +
$"{user.DisplayName,-20}" +
$"{(lastPasswordSet?.ToString("yyyy-MM-dd") ?? "N/A"),-20}" +
$"{(estimatedPasswordExpiry?.ToString("yyyy-MM-dd") ?? "N/A"),-20}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"發生錯誤: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($"內部錯誤: {ex.InnerException.Message}");
}
}

Console.WriteLine("\n按任意鍵退出...");
Console.ReadKey();