/
Get-LogonHistory-Mult.ps1
440 lines (352 loc) · 21.9 KB
/
Get-LogonHistory-Mult.ps1
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
<#
Скрипт показывает недавнюю историю входа на любом компьютере Windows Server 2003/2008
.Description
Этот скрипт просматривает Security Event Log и выдает сообщения интерактивного входа в систему. (локальный или удаленный rdesktop) и выход из системы
Скрипт должен быть запущен с повышенными привелегиями и правами чтения Security Event Log на удаленой машине. (прим. Domain Admins)
.Outputs
System.Management.Automation.PSCustomObject
Get-LogonHistory returns a custom object containing the following properties:
[String]UserName
The username of the account that logged on/off of the machine.
[String]ComputerName
The name of the computer that the user logged on to/off of.
[String]Action
The action the user took with regards to the computer. Either 'logon' or 'logoff'.
[String]LogonType
Either 'console' or 'remote', depending on how the user logged on. This property is null if the user logged off.
[DateTime]TimeStamp
A DateTime object representing the date and time that the user logged on/off.
.Notes
.Example
.\Get-LogonHistory.ps1
Description
-----------
Gets the available logon entries in the Security log on the local computer.
.Example
Invoke-Command -ComputerName 'remotecomputer' -File '.\Get-LogonHistory.ps1'
Description
-----------
Gets the available logon entries in the Security log on a remote computer named 'remotecomputer'.
#>
function Get-Win2008LogonHistory-en {
$user=$null #обнуление переменной $user от возможного мусора предыдущего запуска скрипта
$logons = Get-EventLog Security -computername $_ -AsBaseObject -InstanceId 4624 -after $date |
Where-Object { ($_.Message -match "Logon Type:\s+2") `
-or ($_.Message -match "Logon Type:\s+10") }
$events = $logons | Sort-Object TimeGenerated
if ($events) {
foreach($event in $events) {
# Parse logon data from the Event (Поиск событий входа).
if ($event.InstanceId -eq 4624) {
# A user logged on (Пользователь залогинился).
$action = 'logon'
$event.Message -match "Logon Type:\s+(\d+)" | Out-Null
$logonTypeNum = $matches[1]
# Determine logon type (Определение типа входа).
if ($logonTypeNum -eq 2) {
$logonType = 'console'
} elseif ($logonTypeNum -eq 10) {
$logonType = 'remote'
} else {
$logonType = 'other'
}
# Determine user (Определение пользователя).
if ($event.message -match "New Logon:\s*Security ID:\s*.*\s*Account Name:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
} elseif ($event.InstanceId -eq 4647) {
# A user logged off.
$action = 'logoff'
$logonType = $null
# Determine user (Определение пользователя).
if ($event.message -match "Subject:\s*Security ID:\s*.*\s*Account Name:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
} elseif ($event.InstanceId -eq 41) {
# The computer crashed.
$action = 'logoff'
$logonType = $null
$user = '*'
}
# Determine Account Domain (Определение домена пользователя).
if ($event.message -match "Account Domain:\s*(\w+\S\w+\S\w+)") {
$UserDomain = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
# As long as we managed to parse the Event, print output (После разбора лога фомируем наконец вывод).
if ($user) {
$aduser = Get-ADuser $user -Properties name, samaccountname, mail,telephonenumber | Select-Object name, samaccountname, mail, telephonenumber
$timeStamp = Get-Date $event.TimeGenerated
$output = New-Object -Type PSCustomObject
Add-Member -MemberType NoteProperty -Name 'TimeStamp' -Value $timeStamp -InputObject $output
Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
Add-Member -MemberType NoteProperty -Name 'User Domain' -Value $UserDomain -InputObject $output
Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $Event.MachineName -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Action' -Value $action -InputObject $output
Add-Member -MemberType NoteProperty -Name 'LogonType' -Value $logonType -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Mail' -Value $aduser.Mail -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Telephonenumber' -Value $aduser.telephoneNumber -InputObject $output
Write-Output $output | FT
$output | ConvertTo-Html | Add-Content C:\script\UserProperties.html
$output | Export-Csv -Append -Path C:\script\getuser.csv -Encoding 'UTF8' -force
}
}
} else {
Write-Host "No recent logon/logoff events ( Не обнаружено свежих записей о событиях входа в журнале )."
}
}
function Get-Win2003LogonHistory-en {
$user=$null #обнуление переменной $user от возможного мусора предыдущего запуска скрипта
$logons = Get-EventLog Security -computername $_ -AsBaseObject -InstanceId 528 -after $date |
Where-Object {($_.Message -match "Logon Type:\s+2") `
-or ($_.Message -match "Logon Type:\s+10") }
#$poweroffs = Get-Eventlog System -AsBaseObject -InstanceId 41
$events = $logons | Sort-Object TimeGenerated
if ($events) {
foreach($event in $events) {
# Parse logon data from the Event (Поиск событий входа).
if ($event.InstanceId -eq 528) {
# A user logged on (Пользователь залогинился).
$action = 'logon'
$event.Message -match "Logon Type:\s+(\d+)" | Out-Null
$logonTypeNum = $matches[1]
# Determine logon type (Определение типа входа).
if ($logonTypeNum -eq 2) {
$logonType = 'console'
} elseif ($logonTypeNum -eq 10) {
$logonType = 'remote'
} else {
$logonType = 'other'
}
# Determine user (Определение пользователя).
if ($event.message -match "Successful Logon:\s*User Name:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
} elseif ($event.InstanceId -eq 551) {
# A user logged off.
$action = 'logoff'
$logonType = $null
# Determine user (Определение пользователя).
if ($event.message -match "User initiated logoff:\s*User Name:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
}
# Determine Account Domain (Определение домена пользователя).
if ($event.message -match "Domain:\s*(\w+\S\w+\S\w+)") {
$UserDomain = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
# As long as we managed to parse the Event, print output (После разбора лога фомируем наконец вывод).
if ($User) {
$aduser = Get-ADuser $user -Properties name, samaccountname, mail,telephonenumber | Select-Object name, samaccountname, mail, telephonenumber
$timeStamp = Get-Date $event.TimeGenerated
$output = New-Object -Type PSCustomObject
Add-Member -MemberType NoteProperty -Name 'TimeStamp' -Value $timeStamp -InputObject $output
Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
Add-Member -MemberType NoteProperty -Name 'User Domain' -Value $UserDomain -InputObject $output
Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $Event.MachineName -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Action' -Value $action -InputObject $output
Add-Member -MemberType NoteProperty -Name 'LogonType' -Value $logonType -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Mail' -Value $aduser.Mail -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Telephonenumber' -Value $aduser.telephoneNumber -InputObject $output
Write-output $output | FT
$output | ConvertTo-Html | add-content C:\script\UserProperties.html
$output | Export-Csv -Append -Path C:\script\getuser.csv -Encoding 'UTF8' -force
Write-Host "."
}
}
} else {
Write-Host "No recent logon/logoff events ( Не обнаружено свежих записей о событиях входа в журнале )."
}
}
function Get-Win2008LogonHistory-ru {
$user=$null #обнуление переменной $user от возможного мусора предыдущего запуска скрипта
$logons = Get-EventLog Security -computername $_ -AsBaseObject -InstanceId 4624,4647 -after $date |
Where-Object {($_.Message -match "Тип входа:\s+2") `
-or ($_.Message -match "Тип входа:\s+10") }
#$poweroffs = Get-EventLog System -AsBaseObject -InstanceId 41
$events = $logons | Sort-Object TimeGenerated
if ($events) {
foreach($event in $events) {
# Parse logon data from the Event (Поиск событий входа).
if ($event.InstanceId -eq 4624) {
# A user logged on (Пользователь залогинился).
$action = 'logon'
$event.Message -match "Тип входа:\s+(\d+)" | Out-Null
$logonTypeNum = $matches[1]
# Determine logon type (Определение типа входа).
if ($logonTypeNum -eq 2) {
$logonType = 'console'
} elseif ($logonTypeNum -eq 10) {
$logonType = 'remote'
} else {
$logonType = 'other'
}
# Determine user (Определение пользователя).
if ($event.message -match "Новый вход:\s*ИД безопасности:\s*.*\s*Имя учетной записи:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Не удалось разобрать журнал 'Безопасность'. Искаженная запись? Index: $index"
}
} elseif ($event.InstanceId -eq 4647) {
# A user logged off.
$action = 'logoff'
$logonType = $null
# Determine user (Определение пользователя).
if ($event.message -match "Субъект:\s*ИД безопасности:\s*.*\s*Имя учетной записи:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Не удалось разобрать журнал 'Безопасность'. Искаженная запись? Index: $index"
}
} elseif ($event.InstanceId -eq 41) {
# The computer crashed.
$action = 'logoff'
$logonType = $null
$user = '*'
}
# Determine Account Domain (Определение домена пользователя).
if ($event.message -match "Домен учетной записи:\s*(\w+\S\w+\S\w+)") {
$UserDomain = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
# As long as we managed to parse the Event, print output.
if ($user) {
$aduser = Get-ADuser $user -Properties name, samaccountname, mail,telephonenumber | Select-Object name, samaccountname, mail, telephonenumber
$timeStamp = Get-Date $event.TimeGenerated
$output = New-Object -Type PSCustomObject
Add-Member -MemberType NoteProperty -Name 'TimeStamp' -Value $timeStamp -InputObject $output
Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
Add-Member -MemberType NoteProperty -Name 'User Domain' -Value $UserDomain -InputObject $output
Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $Event.MachineName -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Action' -Value $action -InputObject $output
Add-Member -MemberType NoteProperty -Name 'LogonType' -Value $logonType -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Mail' -Value $aduser.Mail -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Telephonenumber' -Value $aduser.telephoneNumber -InputObject $output
Write-Output $output | FT
$output | ConvertTo-Html | Add-Content C:\script\UserProperties.html
$output | Export-Csv -Append -Path C:\script\getuser.csv -Encoding 'UTF8' -force
}
}
} else {
Write-Host "No recent logon/logoff events ( Не обнаружено свежих записей о событиях входа в журнале )."
}
}
function Get-Win2003LogonHistory-ru {
$user=$null #обнуление переменной $user от возможного мусора предыдущего запуска скрипта
$logons = Get-EventLog Security -computername $_ -AsBaseObject -InstanceId 528 -after $date |
Where-Object {($_.Message -match "Тип входа:\s+2") `
-or ($_.Message -match "Тип входа:\s+10") }
#$poweroffs = Get-Eventlog System -AsBaseObject -InstanceId 41
$events = $logons | Sort-Object TimeGenerated
if ($events) {
foreach($event in $events) {
# Parse logon data from the Event.
if ($event.InstanceId -eq 528) {
# A user logged on.
$action = 'logon'
$event.Message -match "Тип входа:\s+(\d+)" | Out-Null
$logonTypeNum = $matches[1]
# Determine logon type.
if ($logonTypeNum -eq 2) {
$logonType = 'console'
} elseif ($logonTypeNum -eq 10) {
$logonType = 'remote'
} else {
$logonType = 'other'
}
# Determine user.
if ($event.message -match "Успешный вход в систему:\s*Пользователь:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Не удалось разобрать журнал 'Безопасность'. Искаженная запись? Index: $index"
}
} elseif ($event.InstanceId -eq 551) {
# A user logged off.
$action = 'logoff'
$logonType = $null
# Determine user.
if ($event.message -match "Выход, вызванный пользователем:\s*Пользователь:\s*(\w+\S\w+\S\w+)") {
$user = $matches[1]
} else {
$index = $event.index
Write-Warning "Не удалось разобрать журнал 'Безопасность'. Искаженная запись? Index: $index"
}
}
# Determine Account Domain (Определение домена пользователя).
if ($event.message -match "Домен:\s*(\w+\S\w+\S\w+)") {
$UserDomain = $matches[1]
} else {
$index = $event.index
Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
}
# As long as we managed to parse the Event, print output.
if ($User) {
$aduser = Get-ADuser $user -Properties name, samaccountname, mail,telephonenumber | Select-Object name, samaccountname, mail, telephonenumber
$timeStamp = Get-Date $event.TimeGenerated
$output = New-Object -Type PSCustomObject
Add-Member -MemberType NoteProperty -Name 'TimeStamp' -Value $timeStamp -InputObject $output
Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
Add-Member -MemberType NoteProperty -Name 'User Domain' -Value $UserDomain -InputObject $output
Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $Event.MachineName -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Action' -Value $action -InputObject $output
Add-Member -MemberType NoteProperty -Name 'LogonType' -Value $logonType -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Mail' -Value $aduser.Mail -InputObject $output
Add-Member -MemberType NoteProperty -Name 'Telephonenumber' -Value $aduser.telephoneNumber -InputObject $output
Write-output $output | FT
$output | ConvertTo-Html | add-content C:\script\UserProperties.html
$output | Export-Csv -Append -Path C:\script\getuser.csv -Encoding 'UTF8' -force
}
}
} else {
Write-Host "No recent logon/logoff events ( Не обнаружено свежих записей о событиях входа в журнале )."
}
}
Import-Module ActiveDirectory
$Date = $null
$Day = $null
$Day = Read-Host "Enter count of several last days for parse log ( Введите количество дней за которые надо собрать информацию из лога )"
$Date = (Get-Date).AddDays(-$Day)
$ComputerName = $Null
$ComputerName = Read-Host "Enter computer name for analysis ( Введите имя компьютера для анализа )"
#$ComputerName = (Import-Csv -Path C:\script\computers.csv).name
$ComputerName | ForEach-Object {
$OSversion = (Get-WmiObject -computername $_ -Query 'SELECT version FROM Win32_OperatingSystem').version
$OSLanguage = (Get-WmiObject -computername $_ -Query 'SELECT oslanguage FROM Win32_OperatingSystem').oslanguage
if (($OSversion -ge 6) -and ($OSLanguage -eq 1049))
{ "Сбор событий журнала Security на компьютере $_ (Windows 2008 RU)"
Get-Win2008LogonHistory-rus
} else {
if (($OSversion -ge 6) -and ($OSLanguage -eq 1033)) {
"Сбор событий журнала Security на компьютере $_ (Windows 2008 EN)"
Get-Win2008LogonHistory-en
} elseif ($OSLanguage -ge 1049) {
"Сбор событий журнала Security на компьютере $_ (Windows 2003 RU)"
Get-Win2003LogonHistory-rus
}
else {
"Сбор событий журнала Security на компьютере $_ (Windows 2003 EN)"
Get-Win2003LogonHistory-en
}
}
}