DateTime startDate = new DateTime(2025, 2, 15); // 例如,從2023年1月1日開始
EventLog eventLog = new EventLog();
eventLog.Log = "Security"; // 可以更改為 "System" 或 "Security" 等
eventLog.Source = "Application"; // 根據需要設置,通常為應用程序名稱或"Application"
// 獲取所有條目
var entries = eventLog.Entries;
// 過濾出指定日期后的條目
var filteredEntries = entries.Cast<EventLogEntry>()
.Where(e => e.TimeGenerated > startDate)
.ToList();
int tmpNum = 0;
foreach (var entry in filteredEntries)
{
//Console.WriteLine($"Time: {entry.TimeGenerated}, Message: {entry.Message}");
if (entry.EventID == 4624 || entry.EventID == 4625 || entry.EventID == 4778)
{
tmpNum++;
// 解析用戶信息,這里簡單地從消息中提取用戶名,不同系統的事件消息格式可能略有不同,需根據實際情況調整解析邏輯
string message = entry.Message;
string tmpMessage = message;
int startIndex = 0;
int endIndex = 0;
if (entry.EventID == 4624 || entry.EventID == 4625)
{
string tmpFirstStr = "";
if (entry.EventID == 4624) { tmpFirstStr = "新登錄:"; }
if (entry.EventID == 4625) { tmpFirstStr = "登錄失敗的帳戶:"; }
startIndex = message.IndexOf(tmpFirstStr) + tmpFirstStr.Length;
tmpMessage = message.Substring(startIndex, message.Length - startIndex);
}
//獲取登錄用戶名
string latestLoginUser = string.Empty;
string tmpUserNameInfo = "";
if (entry.EventID == 4778 || entry.EventID == 4625) { tmpUserNameInfo = "帳戶名:"; }
if (entry.EventID == 4624) { tmpUserNameInfo = "帳戶名稱:"; }
startIndex = tmpMessage.IndexOf(tmpUserNameInfo) + tmpUserNameInfo.Length;
endIndex = tmpMessage.IndexOf(Environment.NewLine, startIndex);
if (startIndex > 0 && endIndex > startIndex)
{
latestLoginUser = tmpMessage.Substring(startIndex, endIndex - startIndex).Trim();
}
//獲取登錄IP地址
string latestLoginIP = string.Empty;
string tmpUserIpInfo = "";
if (entry.EventID == 4624 || entry.EventID == 4625) { tmpUserIpInfo = "源網絡地址:"; }
if (entry.EventID == 4778) { tmpUserIpInfo = "客戶端地址:"; }
startIndex = tmpMessage.IndexOf(tmpUserIpInfo) + tmpUserIpInfo.Length;
endIndex = tmpMessage.IndexOf(Environment.NewLine, startIndex);
if (startIndex > 0 && endIndex > startIndex)
{
latestLoginIP = tmpMessage.Substring(startIndex, endIndex - startIndex).Trim();
}
//登錄結果
string tmpLoginResult = "";
if (entry.EventID == 4778 || entry.EventID == 4624) { tmpLoginResult = "成功。"; }
if (entry.EventID == 4625)
{
tmpLoginResult = "失敗。";
string tmpErrorInfo = " 失敗原因:";
startIndex = tmpMessage.IndexOf(tmpErrorInfo) + tmpErrorInfo.Length;
endIndex = tmpMessage.IndexOf(Environment.NewLine, startIndex);
if (startIndex > 0 && endIndex > startIndex)
{
tmpLoginResult = tmpErrorInfo + tmpMessage.Substring(startIndex, endIndex - startIndex).Trim();
}
}
Console.WriteLine($"第 {tmpNum} 次登錄(" + entry.EventID + ",時間:" + entry.TimeGenerated);
Console.WriteLine("登錄帳戶名:" + latestLoginUser);
Console.WriteLine("登錄IP地址:" + latestLoginIP);
Console.WriteLine("登錄結果:" + tmpLoginResult);
}
}