Нужно получить историю входы выхода пользователей из системы

Поиск  Пользователи  Правила 
Закрыть
Логин:
Пароль:
Забыли свой пароль?
Регистрация
Войти
 
Страницы: 1
Ответить
Нужно получить историю входы выхода пользователей из системы
У меня терминальный сервер 2008 как достать историю логон\логоф пользователей.
Сначала попробую описать где посмотреть глазками историю заходов в виндов. Нужно зайти в журнал событий – безопасность и искать вот это Logon, Special Logon, Logoff and other details.  Вас собственно интересуют вот эти Event ID:
--- начинается вот с этого.
4776 проверка учных данных
4672 специальный вход
-- 4672 может быть много.
4672 специальный вход
4624 вход в систему
--- вот такая группа событий происходит при логоне, и искать их глазками проктически нереально если учесть что такахи событий особенно 4672 может происходить пачками. Скрипт для автоматизации процесса делающий тоже самое через wmi: (скрипт запускать через powershell)

<#
.Synopsis
   Extracts recent logon history for the local machine from the Security Event Log.
.Description
   This script scans through the Security Event Log on the local machine for interactive logons (both local and remote), and logouts.
   
   It then constructs a PowerShell Custom Object containing the fields of interest and writes that object to the pipeline as its output.
   
   NOTE: This script must be run 'As Administrator' in order to access the Security Event Log.
   
   To run this function on a remote computer, use it in conjunction with the Invoke-Command cmdlet.
.Inputs
   None. You cannot pipe input to this script.
.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-Win7LogonHistory {
   $logons = Get-EventLog Security -AsBaseObject -InstanceId 4624,4647 |
             Where-Object { ($_.InstanceId -eq 4647) `
                       -or (($_.InstanceId -eq 4624) -and ($_.Message -match "Logon Type:\s+2")) `
                       -or (($_.InstanceId -eq 4624) -and ($_.Message -match "Logon Type:\s+10")) }
   $poweroffs = Get-EventLog System -AsBaseObject -InstanceId 41
   $events = $logons + $poweroffs | 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+)") {
                   $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+)") {
                   $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 = '*'
           }
       
           # As long as we managed to parse the Event, print output.
           if ($user) {
               $timeStamp = Get-Date $event.TimeGenerated
               $output = New-Object -Type PSCustomObject
               Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
               Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $env:computername -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 'TimeStamp' -Value $timeStamp -InputObject $output
               Write-Output $output
           }
       }
   } else {
       Write-Host "No recent logon/logoff events."
   }
}

function Get-WinXPLogonHistory {
   $logons = Get-EventLog Security -AsBaseObject -InstanceId 528,551 |
             Where-Object { ($_.InstanceId -eq 551) `
                       -or (($_.InstanceId -eq 528) -and ($_.Message -match "Logon Type:\s+2")) `
                       -or (($_.InstanceId -eq 528) -and ($_.Message -match "Logon Type:\s+10")) }
   #$poweroffs = Get-Eventlog System -AsBaseObject -InstanceId 6008
   #$events = $logons + $poweroffs | 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+)") {
                   $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+)") {
                   $user = $matches[1]
               } else {
                   $index = $event.index
                   Write-Warning "Unable to parse Security log Event. Malformed entry? Index: $index"
               }
           }# elseif ($event.InstanceId -eq 6008) {
               # The computer crashed.
           #    $action = 'logoff'
           #    $logonType = $null
           #    $user = '*'
           #}
       
           # As long as we managed to parse the Event, print output.
           if ($user) {
               $timeStamp = Get-Date $event.TimeGenerated
               $output = New-Object -Type PSCustomObject
               Add-Member -MemberType NoteProperty -Name 'UserName' -Value $user -InputObject $output
               Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $env:computername -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 'TimeStamp' -Value $timeStamp -InputObject $output
               Write-Output $output
           }
       }
   } else {
       Write-Host "No recent logon/logoff events."
   }
}
$OSversion = (Get-WmiObject -Query 'SELECT version FROM Win32_OperatingSystem').version
if ($OSversion -ge 6) {
   Get-Win7LogonHistory
} else {
   Get-WinXPLogonHistory
}
Услуги Системного Администратора - Работаю только с Юр. Лицами по договору обслуживания.
Вот скрипт и небольшая история к нему:
# Очищаем экран
clear

# Получаем список компьютеров из определенной OU в ActiveDirectory
# засовываем их в массив.
$allServers = @(Get-ADComputer -filter * `
-searchBase "OU=Servers,OU=AllComputers,DC=kisliak,DC=local")


# Подставляем каждый из серверов и проверяем используются ли необходимая
# учетная запись для запуска какой-нибудь службы на компьютере.
$allServers | Foreach-Object {Get-Date; Write-Host ':::::::: Computer Name is :::::::::' `
$_.Name ; Get-WmiObject Win32_Service -computername $_.Name | `
where{($_.StartName -contains 'KISLIAK\needuser') -or ($_.StartName -eq 'ntbackup@best.local')}}


# Подставляем имя каждого ПК из массива в скрипт и осуществляем поиск
# в Security журнале на присутствие искомой учетной записи в качестве вхождения на сервер.
$allServers | Foreach-Object {Get-Date; Write-Host ':::::::: Computer Name is :::::::::' `
$_.Name; Get-EventLog -computername $_.Name -LogName Security |
where{$_.ReplacementStrings -contains 'needuser'}}    


Итак, исходные данные следующие: существует учетная запись в ActiveDirectory, каждую ночь видно, что под ней выполняется вход на какой-то объект в инфраструктуре(компьютер/сервер), но никто не знает, где данная учетная запись работает и что она делает. Просто отключать ее нельзя, т.к. существуют критичные системы работу которых нарушать ни в коем случае нельзя.


Возможно существуют простые методы поиска, но я до них не додумался, по этому решил написать скрипт на PowerShell, который получит имена всех серверов, поместит их в массив далее пробежит по всем серверам из списка и проверит нет ли нашей учетной записи в качестве LogOnAs пользователя, положительный результат я тут не получил.

После проверки в сервисах, я решил проверить на наличие входа данной учетной записи на сервер, и проверять это решил в Security логе, т.к. в нем регистрируются все успешные и не успешные входы на сервер.

Лог обрабатывается довольно долго, по этому мои, примерно 150 серверов, обрабатывались почти всю ночь, но положительного результата я всеже добился и нашел то, что искал.
Услуги Системного Администратора - Работаю только с Юр. Лицами по договору обслуживания.
Страницы: 1
Ответить
Форма ответов
Текст сообщения*
:) ;) :D 8-) :( :| :cry: :evil: :o :oops: :{} :?: :!: :idea:
Защита от автоматических сообщений. Введите символы, изображенные на этой картинке в поле ввода &quote;Код подтверждения&quote;.