using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Globalization;
using System.Linq;
class Program
{
static void Main()
{
// 獲取最近一天的時間
DateTime oneDayAgo = DateTime.Now.AddDays(-1);
// 事件日志查詢條件
string query = @"<QueryList>
<Query Id='0' Path='Security'>
<Select Path='Security'>
*[System[
(EventID=4624 or EventID=4625)
and TimeCreated[@SystemTime >= '" + oneDayAgo.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture) + @"']
]]
</Select>
</Query>
</QueryList>";
List<RemoteDesktopLoginInfo> loginInfos = new List<RemoteDesktopLoginInfo>();
using (EventLogQuery eventLogQuery = new EventLogQuery("Security", PathType.LogName, query))
using (EventLogReader eventLogReader = new EventLogReader(eventLogQuery))
{
EventRecord eventRecord;
while ((eventRecord = eventLogReader.ReadEvent())!= null)
{
bool isSuccess = eventRecord.Id == 4624;
string account = eventRecord.Properties[5].Value.ToString();
DateTime loginTime = eventRecord.TimeCreated.Value;
string ip = eventRecord.Properties[18].Value.ToString();
loginInfos.Add(new RemoteDesktopLoginInfo
{
Account = account,
LoginTime = loginTime,
IP = ip,
IsSuccess = isSuccess
});
}
}
// 按登錄時間降序排序
loginInfos = loginInfos.OrderByDescending(info => info.LoginTime).ToList();
// 輸出結果
foreach (var info in loginInfos)
{
Console.WriteLine($"賬號: {info.Account}");
Console.WriteLine($"登錄時間: {info.LoginTime}");
Console.WriteLine($"IP: {info.IP}");
Console.WriteLine($"登錄結果: {(info.IsSuccess? "成功" : "失敗")}");
Console.WriteLine("---------------------------");
}
}
}
class RemoteDesktopLoginInfo
{
public string Account { get; set; }
public DateTime LoginTime { get; set; }
public string IP { get; set; }
public bool IsSuccess { get; set; }
}