以下是一個示例代碼,用于獲取Windows Server系統最新的遠程桌面登錄信息。它通過查詢Windows事件日志(特別是“Microsoft - Windows - TerminalServices - LocalSessionManager/Operational”日志中的相關事件)來實現:
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
string latestLoginUser = string.Empty;
DateTime latestLoginTime = DateTime.MinValue;
try
{
EventLog eventLog = new EventLog("Microsoft - Windows - TerminalServices - LocalSessionManager/Operational", ".");
foreach (EventLogEntry entry in eventLog.Entries)
{
if (entry.EventID == 1149 && entry.EntryType == EventLogEntryType.Information)
{
DateTime entryTime = entry.TimeGenerated;
if (entryTime > latestLoginTime)
{
latestLoginTime = entryTime;
string message = entry.Message;
int startIndex = message.IndexOf("user name: ") + "user name: ".Length;
int endIndex = message.IndexOf(Environment.NewLine, startIndex);
if (startIndex > 0 && endIndex > startIndex)
{
latestLoginUser = message.Substring(startIndex, endIndex - startIndex).Trim();
}
}
}
}
if (!string.IsNullOrEmpty(latestLoginUser))
{
Console.WriteLine($"最新的遠程桌面登錄信息:");
Console.WriteLine($"登錄用戶:{latestLoginUser}");
Console.WriteLine($"登錄時間:{latestLoginTime}");
}
else
{
Console.WriteLine("未找到遠程桌面登錄信息。");
}
}
catch (Exception ex)
{
Console.WriteLine($"發生錯誤:{ex.Message}");
}
}
}
注意事項:
1. 運行此程序需要有足夠的權限來訪問事件日志,通常需要以管理員身份運行。
2. 不同版本的Windows Server系統,事件日志的名稱、事件ID以及事件消息的格式可能會有所不同,如果在實際使用中發現無法正確獲取信息,需要根據具體環境調整代碼中的事件日志名稱、事件ID和消息解析邏輯等內容。
3. 此代碼僅作為示例,實際應用中可能還需要考慮更多的異常處理和兼容性問題。
該文章在 2025/2/14 17:35:35 編輯過