forked from imhomos/ldappack
/
Program.cs
207 lines (168 loc) · 7.04 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using Unosquare.Swan;
using Unosquare.Swan.Formatters;
namespace LdapPack
{
class Program
{
private static void GetLdapInfo(Action<SearchResult> callback, string filter, string[] propertiesToLoad)
{
foreach (DomainController controller in Domain.GetCurrentDomain().DomainControllers)
{
$"Querying: {controller.Name}".Info();
try
{
using (var directoryEntry = new DirectoryEntry($"LDAP://{controller.Name}"))
{
using (var searcher = new DirectorySearcher(directoryEntry))
{
searcher.PageSize = 1000;
searcher.Filter = filter;
searcher.PropertiesToLoad.AddRange(propertiesToLoad);
foreach (SearchResult searchResult in searcher.FindAll())
{
callback(searchResult);
}
}
}
}
catch (Exception ex)
{
ex.Message.Error();
$"Domain controller {controller.Name} is not responding.".Error();
}
}
}
private static void GetStaleUsers()
{
var data = new Dictionary<string, DateTime>();
var callback = new Action<SearchResult>((searchResult) =>
{
if (!searchResult.Properties.Contains("lastLogon")) return;
var lastLogOn = DateTime.FromFileTime((long) searchResult.Properties["lastLogon"][0]);
var username = searchResult.Properties["distinguishedName"][0].ToString();
if (data.ContainsKey(username))
{
if (lastLogOn > data[username])
{
data[username] = lastLogOn;
}
}
else
{
data.Add(username, lastLogOn);
}
});
GetLdapInfo(callback,
"(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
new[] {"distinguishedName", "lastLogon" });
if (data.Count == 0)
{
"Found no data".Warn();
return;
}
$"Found {data.Count} records".Info();
var days = "How many days before?".ReadNumber(30);
var filtered = data.Where(x => x.Value < DateTime.Now.AddDays(-days)).OrderBy(x => x.Key);
foreach (var item in filtered)
$"{item.Key} - {item.Value}".Info();
$"Filtered {filtered.Count()} records".Info();
if ("Do you want to export to CSV? (y)".ReadKey().Key != ConsoleKey.Y) return;
var filename = Runtime.GetDesktopFilePath("ldap-stale-users.csv");
CsvWriter.SaveRecords(filtered, filename);
$"Export done {filename}".Info();
if ("Do you want to open the file? (y)".ReadKey().Key != ConsoleKey.Y) return;
(new Process()
{
StartInfo = new ProcessStartInfo {FileName = filename}
}).Start();
}
private static void GetStaleComputers()
{
var data = new Dictionary<string, Tuple<DateTime, string>>();
var callback = new Action<SearchResult>((searchResult) =>
{
if (!searchResult.Properties.Contains("PwdLastSet")) return;
var pwdLastSet = DateTime.FromFileTime((long) searchResult.Properties["PwdLastSet"][0]);
var username = searchResult.Properties["distinguishedName"][0].ToString();
var operatingsystem = searchResult.Properties.GetValue("operatingsystem");
if (data.ContainsKey(username))
{
if (pwdLastSet > data[username].Item1)
{
data[username] = new Tuple<DateTime, string>(pwdLastSet, operatingsystem);
}
}
else
{
data.Add(username, new Tuple<DateTime, string>(pwdLastSet, operatingsystem));
}
});
GetLdapInfo(callback,
"(&(objectCategory=computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(!(isCriticalSystemObject=TRUE)))",
new[] {"PwdLastSet", "distinguishedName", "operatingsystem", "lastLogonTimeStamp " });
if (data.Count == 0)
{
"Found no data".Warn();
return;
}
$"Found {data.Count} records".Info();
var days = "How many days before?".ReadNumber(30);
var filtered = data.Select(x => new
{
Computer = x.Key,
OperatingSystem = x.Value.Item2,
Stale = x.Value.Item1 < DateTime.Now.AddDays(-days) ? "TRUE" : "FALSE"
}).ToList();
foreach (var item in filtered)
$"{item.Computer} - {item.OperatingSystem} - {item.Stale}".Info();
if ("Do you want to export to CSV? (y)".ReadKey().Key != ConsoleKey.Y) return;
var filename = Runtime.GetDesktopFilePath("ldap-stale-computers.csv");
CsvWriter.SaveRecords(filtered, filename);
$"Export done {filename}".Info();
if ("Do you want to open the file? (y)".ReadKey().Key != ConsoleKey.Y) return;
(new Process()
{
StartInfo = new ProcessStartInfo { FileName = filename }
}).Start();
}
static void Main(string[] args)
{
Runtime.WriteWelcomeBanner();
var options = new Dictionary<ConsoleKey, string>()
{
{ConsoleKey.U, "Get stale users"},
{ConsoleKey.C, "Get stale computers"}
};
var continueLoop = true;
while (continueLoop)
{
var response = "Choose an option".ReadPrompt(options, "Press any key to close...");
switch (response.Key)
{
case ConsoleKey.U:
GetStaleUsers();
break;
case ConsoleKey.C:
GetStaleComputers();
break;
default:
continueLoop = false;
break;
}
}
}
}
static class Extensions
{
public static string GetValue(this ResultPropertyCollection coll, string key)
{
return coll[key].Count > 0 ? coll[key][0].ToString() : null;
}
}
}