【C#】读取Windows系统事件查看器中最新远程桌面用户成功或失败登陆记录
|
admin
2025年2月18日 15:47
本文热度 1002
|
:【C#】读取Windows系统事件查看器中最新远程桌面用户成功或失败登陆记录

查询时,需要注意事件查看器中的各个状态码和相应内容,根据内容灵活设计需要提取的内容:
DateTime startDate = new DateTime(2025, 2, 15);
EventLog eventLog = new EventLog();
eventLog.Log = "Security";
eventLog.Source = "Application";
var entries = eventLog.Entries;
var filteredEntries = entries.Cast<EventLogEntry>()
.Where(e => e.TimeGenerated > startDate)
.ToList();
int tmpNum = 0;
foreach (var entry in filteredEntries)
{
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();
}
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);
}
}
操作结果如下:

该文章在 2025/2/18 15:47:58 编辑过