資安相關 – 檢查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();

作者: 林壽山

目前任職於軟體公司研究開發部門,擔任專業處長,專注於.NET C# 開發,並具備豐富的POS 收銀系統與金流整合開發經驗。我精通各類支付系統的設計與開發,包含第三方支付(如綠界、藍新、歐付寶、速買配、馬來西亞 ePay/HappyPay、台新 One 碼)、行動支付(悠遊卡、一卡通、支付寶、微信支付、街口支付)、以及信用卡支付(聯合信用卡)。 熟悉多種開發技術,擅長PHP 網頁開發(CodeIgniter、Laravel 框架)、Delphi 程式設計、資料庫設計、C# WinForm/WebForm 應用開發、ASP.NET MVC、API 串接設計,並具備LINE 串接開發的豐富經驗。 除了技術開發之外,我也熱衷於技術分享,曾擔任台中學校產業學院講師 5 年,培育新一代的軟體開發人才,致力於推動軟體技術的應用與創新。 我對技術充滿熱忱,始終保持學習與探索的心態,期望透過軟體開發為企業與社會創造更大的價值。