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