Created
September 14, 2021 18:42
-
-
Save alexhiggins732/42f25351fb5efc593d5acb9be10321b1 to your computer and use it in GitHub Desktop.
Parse users logon audits from the Windows Event Log
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// <package id="Microsoft.Extensions.Logging" version="5.0.0" targetFramework="net48" /> | |
EventLog eventLog = new EventLog(); | |
eventLog.Log = "Security"; | |
var userNames = new Dictionary<string, int>(); | |
DateTime? logStart = null; | |
foreach (EventLogEntry entry in eventLog.Entries) | |
{ | |
if (logStart == null) | |
logStart = entry.TimeGenerated; | |
//Write your custom code here | |
var s = entry.Category; | |
if (entry.Message.StartsWith("Credential Manager credentials were read")) | |
continue; | |
if (entry.Message.StartsWith("An account was successfully logged on.")) | |
{ | |
var parts = entry.Message | |
.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) | |
.Select(x => x.Replace("\t", "").Trim()) | |
.Where(x => x.StartsWith("Account Name:") || x.StartsWith("Account Domain:")) | |
.Where(x=> x.Split(':')[1]!="-") | |
.ToArray() | |
.ToLookup(x => x.Split(':')[0], x => x.Split(':')[1]); | |
var accountName = parts["Account Name"].First(); | |
var accountDomain = parts["Account Domain"].First(); | |
var userName = $"{accountDomain}\\{accountName}"; | |
if (!userNames.ContainsKey(userName)) | |
{ | |
userNames.Add(userName, 0); | |
} | |
userNames[userName] += 1; | |
Console.WriteLine($"{userName}: {userNames[userName].ToString("N0")} {entry.TimeGenerated}"); | |
} | |
} | |
Console.WriteLine(""); | |
Console.WriteLine("".PadLeft(Console.BufferWidth, '=')); | |
Console.WriteLine(""); | |
Console.WriteLine("Results:"); | |
Console.WriteLine(""); | |
Console.WriteLine($"\t{userNames.Count} logons since {logStart}"); | |
var results = userNames.OrderBy(x=> x.Key).Select(x => $"{x.Key}\t{x.Value.ToString("N0")}"); | |
Console.WriteLine(string.Join(Environment.NewLine, results)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment