Как посмотреть логи в windows server 2012 r2

Содержание

Просмотр системного журнала

Если в работе Windows 2012 появляется какая-то нестабильность, или появляются ошибки запуска\установки приложений, то это может быть связано с появлениями ошибок  в самой операционной системе.

Все системные ошибки и предупреждения можно найти в «Журнале системы«.

В нем сохраняется информация о событиях, записываемых системными компонентами Windows.

Для просмотра и сохранения системного журнала нужно выполнить шаги:

Открыть «Пуск«:

Открыть «Панель управления«:

В «Панели управления» выбрать «Просмотр журналов событий«

В открывшемся окне выбрать «Просмотр событий» -> «Журналы Windows» -> «Система«

Экспорт журнала

Системный журнал в полном объеме можно выгрузить путем нажатия на ссылку «Сохранить все события как…«

После нажатия ссылки  «Сохранить все события как…» нужно выбрать путь и имя файла для сохраняемого журнала.

При сохранении файла возможно появление окна «Отображение сведений«.

В данном окне нужно выбрать пункт «Отображать сведения для следуюших языков: Русский«

Готово

Содержание

Просмотр системного журнала

Если в работе Windows 2012 появляется какая-то нестабильность, или появляются ошибки запускаустановки приложений, то это может быть связано с появлениями ошибок  в самой операционной системе.

Все системные ошибки и предупреждения можно найти в «Журнале системы«.

В нем сохраняется информация о событиях, записываемых системными компонентами Windows.

Для просмотра и сохранения системного журнала нужно выполнить шаги:

Открыть «Пуск«:

Открыть «Панель управления«:

В «Панели управления» выбрать «Просмотр журналов событий«

В открывшемся окне выбрать «Просмотр событий» -> «Журналы Windows» -> «Система«

Экспорт журнала

Системный журнал в полном объеме можно выгрузить путем нажатия на ссылку «Сохранить все события как…«

После нажатия ссылки  «Сохранить все события как…» нужно выбрать путь и имя файла для сохраняемого журнала.

При сохранении файла возможно появление окна «Отображение сведений«.

В данном окне нужно выбрать пункт «Отображать сведения для следуюших языков: Русский«

Готово


First published on TechNet on Sep 30, 2014


[This post comes to us courtesy of Swapnil Rane


from Commercial Technical Support]

This post will reduce your efforts to identify which log to refer to and where to find it. This can be very useful when you are troubleshooting issues on an Essentials server. We have compiled a list of important logs and their associated wizards below. There can be issues where we may have to refer to multiple logs.

Server-side Logs:

In Windows Server Essentials 2012 and 2012 R2, the location of the log files is under

%programdata%MicrosoftWindows ServerLogs

.

Service Integration Log Files:

O365/On-Premise Exchange/Intune

SharedServiceHost-EmailProviderServiceConfig.log

Windows Azure Backup

OnlineBackupGettingStartedWizard.log

Backup Log Files:

Server Backup Configuration wizard

SBCW.log

Server Backup restore wizard

ServerFFR.log

Client Backup Feature server side log

Backup-<date>.log

Client backup database cleanup

RunTask-BackupCleanup.log

Client backup database checker

RunTask-Consistency check

Storage and Devices Log Files:

User/Device management feature

SharedServiceHost-ManagementServiceConfig.log

Storage features

Storageservice.<date>.log

Storage related feature

Storageutil.<date>.log

Azure Backup Log Files:


Location: C:Program FilesWindows Azure Backup AgentTemp

Azure Backup Logs

CBEngineCurr.errlog

Failed Azure Backup Logs

LastBackupFailedFile#####.txt

Other Helpful Log Files:

DC Promo

DCPromo_date.log

Health evaluation schedule task

RunTask-AlertEvaluation.log

Macintosh Clients Status update

RunTask-MacintoshStatusReport.log

Server DNS status

ServerBeacon.log

Customer Experience Improvement

RunTask-SaveCustomerExperienceImprovementProgramData.log

Program and Service Quality Measurement Log Files:

CA Role installation

CA_ROLE_INSTALL.log

Media pack installation (2012 R2)

MediaPackInstalltionWizard.xxxx.log

Media Service (Specially with RWA)

MediaStreamingProvider.log

O365 (Assign/Un-assign Accounts)

TaskStatus-OIMAddin.log

Client-side Logs:

The client-side log files are located in the folder

%programdata%MicrosoftWindows Serverlogs

. They are as:

Client Deployment

ClientDeploy.log

Client package installation Failures

ComputerConnector.log

Client backup restore mount driver

BackupDriverInstaller.log

Client operation for File history Sync

ClientOperator.log

Main log for client launch pad

LaunchPad.log

Password synchronization feature in AAD

PasswordSyncClientAlerts.log

Add-in feature on client

RunTask-Add-in Management.log

Health evaluation schedule task

RunTask-AlertEvaluation.log

Client Backup scheduled task

RunTask-ClientComputeBackkup.log

Connector uninstall cleanup task

RunTask-Connector cleanup.log

Update health definition file from server to client task

RunTask-HealthDefinitionUpdate.log

RDP feature for RWA

RunTask-RDP Group Configuration.log

Client VPN connectivity issues

RunTask-VPN Routes Repair.log

Client network status update

ServerLocator-<date>.log

Client deployment API call (Client deployment fails)

Setupapi.dev.log

Health alert feature

SharedServiceHost-HealthServiceConfig.log

The above logs should be able to guide you through the process of troubleshooting effectively on Essentials relevant issues.

Here is a list of where you can find important log files for Windows Server 2012 Essentials and Windows Server 2012 R2 Essentials.

Server-side Logs:

In Windows Server Essentials 2012 and 2012 R2, the location of the log files is under %programdata%MicrosoftWindows ServerLogs.

Service Integration Log Files:

O365/On-Premise Exchange/Intune   SharedServiceHost-EmailProviderServiceConfig.log
Windows Azure Backup   OnlineBackupGettingStartedWizard.log

Backup Log Files:

Server Backup Configuration wizard SBCW.log
Server Backup restore wizard ServerFFR.log
Client Backup Feature server side log Backup-<date>.log
Client backup database cleanup RunTask-BackupCleanup.log
Client backup database checker RunTask-Consistency check

Storage and Devices Log Files:

User/Device management feature SharedServiceHost-ManagementServiceConfig.log
Storage features Storageservice.<date>.log
Storage related feature Storageutil.<date>.log

Azure Backup Log Files:

Location: C:Program FilesWindows Azure Backup AgentTemp
Azure Backup Logs CBEngineCurr.errlog
Failed Azure Backup Logs LastBackupFailedFile#####.txt

Other Helpful Log Files:

DC Promo DCPromo_date.log
Health evaluation schedule task RunTask-AlertEvaluation.log
Macintosh Clients Status update RunTask-MacintoshStatusReport.log
Server DNS status ServerBeacon.log
Customer Experience Improvement RunTask-SaveCustomerExperienceImprovementProgramData.log

Program and Service Quality Measurement Log Files:

CA Role installation CA_ROLE_INSTALL.log
Media pack installation (2012 R2) MediaPackInstalltionWizard.xxxx.log
Media Service (Specially with RWA) MediaStreamingProvider.log
O365 (Assign/Un-assign Accounts) TaskStatus-OIMAddin.log

Client-side Logs:

The client-side log files are located in the folder %programdata%MicrosoftWindows Serverlogs. They are as:

Client Deployment ClientDeploy.log
Client package installation Failures ComputerConnector.log
Client backup restore mount driver BackupDriverInstaller.log
Client operation for File history Sync ClientOperator.log
Main log for client launch pad LaunchPad.log
Password synchronization feature in AAD PasswordSyncClientAlerts.log
Add-in feature on client RunTask-Add-in Management.log
Health evaluation schedule task RunTask-AlertEvaluation.log
Client Backup scheduled task RunTask-ClientComputeBackkup.log
Connector uninstall cleanup task RunTask-Connector cleanup.log
Update health definition file from server to client task RunTask-HealthDefinitionUpdate.log
RDP feature for RWA RunTask-RDP Group Configuration.log
Client VPN connectivity issues RunTask-VPN Routes Repair.log
Client network status update ServerLocator-<date>.log
Client deployment API call (Client deployment fails) Setupapi.dev.log
Health alert feature SharedServiceHost-HealthServiceConfig.log

Reference – http://blogs.technet.com/b/sbs/archive/2014/09/30/windows-server-essentials-log-files.aspx 

Resources for Small Business

Время прочтения
3 мин

Просмотры 39K

Не так давно, для успешного прохождения аудита на соответствие стандартам PCI DSS, потребовалось включить аудит событий Windows серверов и что самое главное — настроить отправку уведомлений о критичных событиях на E-mail. Для Linux серверов вопрос решается установкой и настройкой OSSEC (ну еще могут понадобиться syslog ws loganalyzer и auditd), для Windows Server 2012 R2 да еще и русской версии он не подошел (в последствии нам таки удалось его адекватно настроить, если будет интересно — смогу описать как). Так что решили искать другие способы…

Первым дело следует включить аудит всех необходимых операций (управление учетными записями и контроль целостности файлов) в доменной политике. И если с аудитом операций над объектами Active Directory все просто, то вот с аудитом файловых операций придется повозиться. Тут, как нельзя кстати, компания Netwrix (не сочтите за рекламу, — компания автор коммерческого софта для аудита) подготовила замечательную статью: «Настройка аудита файловых серверов: подробная инструкция и шпаргалка» (.pdf).

Но вернемся к нашим «костылям». После успешной активации аудита всех необходимых операций и обнаружения в журналах Windows интересующих нас событий, встал вопрос об их отправке на сервер мониторинга… Логично было бы воспользоваться встроенными инструментами («Attach Task To This Event» не самый информативный инструмент, зато «родной» для Windows), но тут всплывает первый любопытный и не приятный момент от Microsoft — «Send an email and Display a message are deprecated for from Windows Server 2012 and Windows 8».

Send an e-mail (deprecated)

Согласно рекомендациям от Microsoft, как замену встроенному «deprecated» функционалу решили использовать скрипты PowerShell для фильтрации журналов и отправки по E-mail, благо есть подробные инструкции:
«Аудит Active Directory средствами Powershell с оповещением об изменениях».
«Аудит удаления и доступа к файлам и запись событий в лог-файл средствами Powershell»
Но тут возникла сложность другого характера: приведенные выше скрипты отсылали на E-mail только заголовки (темы) событий, тело письма было пустым :( При всем при этом — если скрипт PowerShell запустить в PowerShell ISE «as Administrator», то приходит полное сообщение, как и было задумано!

пример скрипта отправки уведомления о событии ‘Заблокирован аккаунт’ — Event ID 4725:

$time =  (get-date) - (new-timespan -min 60)

$Subject = “Заблокирован аккаунт" 
$Theme = “Только что был заблокирован аккаунт” 
$Server = “smtp.server.local” 
$From = “AD@domain.local” 
$To = “support@domain.local” 
$encoding = [System.Text.Encoding]::UTF8

#Выбирается последнее произошедшее событие с таким ID.
$TimeSpan = new-TimeSpan -sec 1
foreach($event in $events)
{
    $PrevEvent = $Event.Запись
    $PrevEvent = $PrevEvent - 1
    $TimeEvent = $Event.TimeCreated
    $TimeEventEnd = $TimeEvent+$TimeSpan
    $TimeEventStart = $TimeEvent- (new-timespan -sec 1)

$Body=Get-WinEvent -maxevents 1 -FilterHashtable @{LogName=”Security”;ID=4725;StartTime=$TimeEventStart;} | Select TimeCreated,@{n=”Account Name”;e={([xml]$_.ToXml()).Event.EventData.Data | ? {$_.Name -eq “TargetUserName”} |%{$_.’#text’}}},@{n=”Computer”;e={([xml]$_.ToXml()).Event.EventData.Data | ? {$_.Name -eq “TargetDomainName”}| %{$_.’#text’}}} 
$body = $body -replace "@{" -replace "}" -replace "=", ": " -replace ";","`n" -replace "TimeCreated","Время события" -replace "^","`n" 
$BodyM = $Body
}
Send-MailMessage -From $From -To $To -SmtpServer $server -Body “$BodyM `n$Theme” -Subject $Subject -Encoding $encoding  

В общем, если у вас есть реально рабочие скрипты для такого случая — милости прошу в комментарии.

Мы же перешли к другому способу (вдохновила вот эта статья: «Мониторинг и оповещение о событиях в журналах Windows: триггеры событий» и выручила эта утилита: sendEmail):

  1. Добавляем в Task Scheduler задание по интересующему нас событию (прямо из журнала «Security» -> «Attach Task To This Event…«

  2. В Actions указываем запуск скрипта, в котором с помощью утилиты wevtutil делаем выборку из журнала и сохраняем результат в файл.

    пример скрипта — выборка событий с Event ID 4726

    del c:Auditquery_ID4726.txt
    wevtutil qe Security /q:"*[System[(EventID=4726)]]" /f:text /rd:true /c:1 > c:Auditquery_ID4726.txt
    
  3. Вторым действием, с помощью утилиты sendEmail отправляем сохраненный файл по назначению:

    пример аргументов для команды запуска sendEmail:

    -f audit_AD@domain.local -s smtp.domain.local:25 -t support@domain.local -m "AD User Account Management - Event ID 426 - Account was Deleted" -a C:Auditquery_ID4726.txt
    

В результате должны получать что-то типа этого:

P.S. Спасибо всем авторам источников, указанных ранее!

Потихоньку все глубже и глубже осваиваю MS Windows 2012. Пускай будет здесь — полезно знать и помнить.

Узнать кто перезагружал систему server 2012
Event Viewer -> Windows Logs -> System (Filter Current Log)
Event id 1074

Event id 6008 — Не штатное выключение сервера. (либо отключали электричество, либо перезагрузили через ilo)

Event id 26 — Сервер выключил УПС по истечении 20 минут. Application popup: System Shutdown

Event id 1076 Выключение системы

Event id 4478 Кто заходит на сервер с помощью RDP

Узнать кто успешно залогинился на сервере Windows Server 2008
Event id 1149

Узнать кто изменял пароль на учетную запись — Event id 4738
Параметр Password Last Set — отмечает дату когда был изменен пароль для учетной записи.
Level: Information

 
Контроллеры доменов

Event ID — (Категория) — Описание

1) 675 или 4771 
(Аудит событий входа в систему)
Событие 675/4771 на контроллере домена указывает на неудачную попытку войти через Kerberos на рабочей станции с доменной учетной записью. Обычно причиной этого является несоответствующий пароль, но код ошибки указывает, почему именно аутентификация была неудачной. Таблица кодов ошибок Kerberos приведена ниже.

2) 676, или Failed 672 или 4768
(Аудит событий входа в систему) 
Событие 676/4768 логгируется для других типов неудачной аутентификации. Таблица кодов Kerberos приведена ниже.
ВНИМАНИЕ: В Windows 2003 Server событие отказа записывается как 672 вместо 676.

3) 681 или Failed 680 или 4776
(Аудит событий входа в систему) 
Событие 681/4776 на контроллере домена указывает на неудачную попытку входа в систему через
NTLM с доменной учетной записью. Код ошибки указывает, почему именно аутентификация была неудачной.
Коды ошибок NTLM приведены ниже.
ВНИМАНИЕ: В Windows 2003 Server событие отказа записывается как 680 вместо 681.

4) 642 или 4738 
(Аудит управления учетными записями)
Событие 642/4738 указывает на изменения в указанной учетной записи, такие как сброс пароля или активация деактивированной до этого учетной записи. Описание события уточняется в соответствие с типом изменения.

5) 632 или 4728; 636 или 4732; 660 или 4756
(Аудит управления учетными записями)
Все три события указывают на то, что указанный пользователь был добавлен в определенную группу. Обозначены Глобальная (Global), Локальная (Local) и Общая (Universal) соответственно для каждого ID.

6) 624 или 4720 
(Аудит управления учетными записями)
Была создана новая учетная запись пользователя

7) 644 или 4740
(Аудит управления учетными записями)
Учетная запись указанного пользователя была заблокирована после нескольких попыток входа

8)  517 или 1102
(Аудит системных событий)
Указанный пользователь очистил журнал безопасности

Вход и выход из системы (Logon/Logoff)

Event Id — Описание

528 или 4624 — Успешный вход в систему
529 или 4625 — Отказ входа в систему – Неизвестное имя пользователя или неверный пароль
530 или 4625 Отказ входа в систему – Вход в систему не был осуществлен в течение обозначенного периода времени
531 или 4625 — Отказ входа в систему – Учетная запись временно деактивирована
532 или 4625 — Отказ входа в систему – Срок использования указанной учетной записи истек
533 или 4625 — Отказ входа в систему – Пользователю не разрешается осуществлять вход в систему на данном компьютере
534 или 4625 или 5461 — Отказ входа в систему – Пользователь не был разрешен запрашиваемый тип входа на данном компьютере
535 или 4625 — Отказ входа в систему – Срок действия пароля указанной учетной записи истек
539 или 4625 — Отказ входа в систему – Учетная запись заблокирована
540 или 4624 — Успешный сетевой вход в систему (Только Windows 2000, XP, 2003)

Типы входов в систему (Logon Types)

Тип входа в систему — Описание

2 — Интерактивный (вход с клавиатуры или экрана системы)
3 — Сетевой (например, подключение к общей папке на этом компьютере из любого места в сети или IIS вход — Никогда не заходил 528 на Windows Server 2000 и выше. См. событие 540)
4 — Пакет (batch) (например, запланированная задача)
5 — Служба (Запуск службы)
7 — Разблокировка (например, необслуживаемая рабочая станция с защищенным паролем скринсейвером)
8 — NetworkCleartext (Вход с полномочиями (credentials), отправленными в виде простого текст. Часто обозначает вход в IIS с “базовой аутентификацией”)
9 — NewCredentials
10 — RemoteInteractive (Терминальные службы, Удаленный рабочий стол или удаленный помощник)
11 — CachedInteractive (вход с кешированными доменными полномочиями, например, вход на рабочую станцию, которая находится не в сети)

Коды отказов Kerberos

Код ошибки — Причина

6 — Имя пользователя не существует
12 — Ограничение рабочей машины; ограничение времени входа в систему
18 — Учетная запись деактивирована, заблокирована или истек срок ее действия
23 — Истек срок действия пароля пользователя
24 — Предварительная аутентификация не удалась; обычно причиной является неверный пароль
32 — Истек срок действия заявки. Это нормальное событие, которое логгируется учетными записями компьютеров
37 — Время на рабочей машины давно не синхронизировалось со временем на контроллере домена

Коды ошибок NTLM

Код ошибки (десятичная система) — Код ошибки (16-ричная система) — Описание

3221225572 — C0000064 — Такого имени пользователя не существует
3221225578 — C000006A — Верное имя пользователя, но неверный пароль
3221226036 — C0000234 — Учетная запись пользователя заблокирована
3221225586 — C0000072 — Учетная запись деактивирована
3221225583 — C000006F — Пользователь пытается войти в систему вне обозначенного периода времени (рабочего времени)
3221225584 — C0000070 — Ограничение рабочей станции
3221225875 — C0000193 — Истек срок действия учетной записи
3221225585 — C0000071 — Истек срок действия пароля
3221226020 — C0000224 — Пользователь должен поменять пароль при следующем входе в систему

В этой статье мы рассмотрим, как получить и проанализировать логи RDP подключений в Windows. Логи RDP подключений позволяют администраторам терминальных RDS серверов/ферм получить информацию о том, какие пользователи подключались к серверу, когда был выполнен вход и когда сеанс завершен, с какого устройства (имя или IP адрес) подключался пользователь.

Описанные методики получения и исследования RDP логов применима как к Windows Server 2022/2019/2016/2012R2, так и для десктопных версий Windows 11, 10, 8.1 c.

Содержание:

  • События RDP подключений в журналах Windows (Event Viewer)
  • Получаем логи RDP подключений в Windows с помощью PowerShell
  • Логи RDP подключений на клиентах Windows

События RDP подключений в журналах Windows (Event Viewer)

Когда пользователь удаленно подключается к RDS серверу или удаленному столу Windows (RDP), информация об этих событиях сохраняется в журналы Windows. Рассмотрим основные этапы RDP подключения и связанные с ними события в Event Viewer.

  1. Network Connection
  2. Authentication
  3. Logon
  4. Session Disconnect/Reconnect
  5. Logoff

Network Connection: – событие установления сетевого подключение к серверу от RDP клиента пользователя. Событие с EventID – 1149 (Remote Desktop Services: User authentication succeeded). Наличие этого события не свидетельствует об успешной аутентификации пользователя. Этот журнал находится в разделе Applications and Services Logs -> Microsoft -> Windows -> Terminal-Services-RemoteConnectionManager -> Operational. Включите фильтр по данному событию (ПКМ по журналу-> Filter Current Log -> EventId 1149).

1149 Terminal-Services-RemoteConnectionManager

С помощью PowerShell можно вывести список всех попыток RDP подключений:

$RDPAuths = Get-WinEvent -LogName 'Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational' -FilterXPath '<QueryList><Query Id="0"><Select>*[System[EventID=1149]]</Select></Query></QueryList>'
[xml[]]$xml=$RDPAuths|Foreach{$_.ToXml()}
$EventData = Foreach ($event in $xml.Event)
{ New-Object PSObject -Property @{
TimeCreated = (Get-Date ($event.System.TimeCreated.SystemTime) -Format 'yyyy-MM-dd hh:mm:ss K')
User = $event.UserData.EventXML.Param1
Domain = $event.UserData.EventXML.Param2
Client = $event.UserData.EventXML.Param3
}
} $EventData | FT

вывести журнал подключений к RDP/RDS серверу с помощью powershell

В результате у вас получится список с историей всех сетевых RDP подключений к данному серверу. В событии содержится имя пользователя, домен (если используется NLA аутентификация, при отключенном NLA текст события выглядит иначе) и IP адрес компьютера пользователя.

Remote Desktop Services: User authentication succeeded

Authentication: – успешная или неудачная аутентификация пользователя на сервере. Журнал Windows -> Security. Здесь нас могут интересовать события с EventID – 4624 (успешная аутентификация — An account was successfully logged on) или 4625 (ошибка аутентификации — An account failed to log on). Обратите внимание на значение LogonType в событии.

  • LogonType = 10 или 3 — при входе через терминальную службу RDP —.
  • LogonType = 7, значит выполнено переподключение к уже существующему RDP сеансу.
  • LogonType = 5 – событие RDP подключения к консоли сервера (в режиме mstsc.exe /admin)

Вы можете использовать события с ошибками аутентификации для защиты от удаленного перебора паролей через RDP. СВы можете автоматически блокировать на файерволе IP адреса, с которых выполняется подбор пароля, простым PowerShell скриптом (см. статью).

rdp событие аутентфикации An account was successfully logged on

При этом имя пользователя содержится в описании события в поле Account Name, имя компьютера в Workstation Name, а имя пользователя в Source Network Address.

Обратите внимание на значение поля LogonID – это уникальный идентификатор сессии пользователя, с помощью которого можно отслеживать дальнейшую активность данного пользователя. Но при отключении от RDP сессии (disconnect) и повторного переподключения к той же сессии, пользователю будет выдан новый TargetLogonID (хотя RDP сессия осталась той же самой).

Вы можете получить список событий успешных авторизаций по RDP (событие 4624) с помощью такой команды PowerShell.

Get-EventLog security -after (Get-date -hour 0 -minute 0 -second 0) | ?{$_.eventid -eq 4624 -and $_.Message -match 'logon type:s+(10)s'} | Out-GridView

получиь журнал RDP входов с помощью PowerShell

Logon: – RDP вход в систему, EventID – 21 (Remote Desktop Services: Session logon succeeded. Это событие появляется после успешной аутентификации пользователя. Этот журнал находится в разделе Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Как вы видите, здесь можно узнать идентификатор RDP сессии для пользователя — Session ID.

Remote Desktop Services: Session logon succeeded

Событие с EventID – 21 (Remote Desktop Services: Shell start notification received) означает успешный запуск оболочки Explorer (появление окна рабочего стола в RDP сессии).

Session Disconnect/Reconnect – события отключения и переподключения к сессии имеют разные коды в зависимости от того, что вызвало отключение пользователя (отключение по неактивности, заданному в таймаутах для RDP сессий; выбор пункта Disconnect в сессии; завершение RDP сессии другим пользователем или администратором и т.д.). Эти события находятся в разделе журналов Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Рассмотрим RDP события, которые могут быть полезными:

  • EventID – 24 (Remote Desktop Services: Session has been disconnected) – пользователь отключился от RDP сессии.
  • EventID – 25 (Remote Desktop Services: Session reconnection succeeded) – пользователь переподключился к своей имеющейся RDP сессии на сервере.
  • EventID – 39 (Session <A> has been disconnected by session <B>) – пользователь сам отключился от своей RDP сессии, выбрав соответствующий пункт меню (а не просто закрыл окно RDP клиента). Если идентификаторы сессий разные, значит пользователя отключил другой пользователь (или администратор).
  • EventID – 40 (Session <A> has been disconnected, reason code <B>). Здесь нужно смотреть на код причины отключения в событии. Например:
    • reason code 0 (No additional information is available) – обычно говорит о том, что пользователь просто закрыл окно RDP клиента.
    • reason code 5 (The client’s connection was replaced by another connection) – пользователь переподключился к своей старой сессии.
    • reason code 11 (User activity has initiated the disconnect) – пользователь сам нажал на кнопку Disconnect в меню.

Событие с EventID – 4778 в журнале Windows -> Security (A session was reconnected to a Window Station). Пользователь переподключился к RDP сессии (пользователю выдается новый LogonID).

Событие с EventID 4779 в журнале Windows -> Security (A session was disconnected from a Window Station). Отключение от RDP сеанса.

Logoff: – выход пользователя из системы. При этом в журнале Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational регистрируется событие с EventID 23 (Remote Desktop Services: Session logoff succeeded).

Remote Desktop Services: Session logoff succeeded

При этом в журнале Security нужно смотреть событие EventID 4634 (An account was logged off).

Событие Event 9009 (The Desktop Window Manager has exited with code (<X>) в журнале System говорит о том, что пользователь инициировал завершение RDP сессии, и окно и графический shell пользователя был завершен.

EventID 4647 — User-initiated logoff

Получаем логи RDP подключений в Windows с помощью PowerShell

Ниже представлен небольшой PowerShell скрипт, который выгружает из журналов терминального RDS сервера историю всех RDP подключений за текущий день. В полученной таблице указано время подключения, IP адрес клиента и имя пользователя (при необходимости вы можете включить в отчет другие типы входов).

Get-EventLog -LogName Security -after (Get-date -hour 0 -minute 0 -second 0)| ?{(4624,4778) -contains $_.EventID -and $_.Message -match 'logon type:s+(10)s'}| %{
(new-object -Type PSObject -Property @{
TimeGenerated = $_.TimeGenerated
ClientIP = $_.Message -replace '(?smi).*Source Network Address:s+([^s]+)s+.*','$1'
UserName = $_.Message -replace '(?smi).*ssAccount Name:s+([^s]+)s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*ssAccount Domain:s+([^s]+)s+.*','$1'
LogonType = $_.Message -replace '(?smi).*Logon Type:s+([^s]+)s+.*','$1'
})
} | sort TimeGenerated -Descending | Select TimeGenerated, ClientIP `
, @{N='Username';E={'{0}{1}' -f $_.UserDomain,$_.UserName}} `
, @{N='LogType';E={
switch ($_.LogonType) {
2 {'Interactive - local logon'}
3 {'Network conection to shared folder)'}
4 {'Batch'}
5 {'Service'}
7 {'Unlock (after screensaver)'}
8 {'NetworkCleartext'}
9 {'NewCredentials (local impersonation process under existing connection)'}
10 {'RDP'}
11 {'CachedInteractive'}
default {"LogType Not Recognised: $($_.LogonType)"}
}
}}

логи RDP подключений к RDS серверу с IP адресами и учетными записями

Можно экспортировать логи RDP подключений из журнала в CSV файл (для дальнейшего анализа в таблице Excel). Экспорт журнала можно выполнить из консоли Event Viewer (при условии что логи не очищены) или через командную строку:

WEVTUtil query-events Security > c:pssecurity_log.txt

Или с помощью PowerShell:

get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:psrdp-log.csv  -Encoding UTF8

Если ваши пользователи подключаются к RDS серверам через шлюз удаленных рабочих столов Remote Desktop Gateway, вы можете обрабатывать логи подключений пользователей по журналу Microsoft-Windows-TerminalServices-Gateway по EventID 302. Например, следующий PowerShell скрипт выведет полную историю подключений через RD Gateway указанного пользователя:

$rdpusername="kbuldogov"
$properties = @(
@{n='User';e={$_.Properties[0].Value}},
@{n='Source IP Adress';e={$_.Properties[1].Value}},
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='Target RDP host';e={$_.Properties[3].Value}}
)
(Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-Gateway/Operational';ID='302'} | Select-Object $properties) -match $rdpusername

powershell поиск в логах удаленных RDP подключений на remote desktop gateway в windows server 2019

Другие события, связанные с подключениями пользователей на RD Gateway в журнале Microsoft-Windows-TerminalServices-Gateway:

  • 300
    The user %1, on client computer %2, met resource authorization policy requirements and was therefore authorized to connect to resource %4
  • 302
    The user %1, on client computer %2, connected to resource %4
  • 303
    The user %1, on client computer %2, disconnected from the following network resource: %4. Before the user disconnected, the client transferred %6 bytes and received %5 bytes. The client session duration was %7 seconds.

Список текущих RDP сессий на сервере можно вывести командой:

qwinsta

Команда возвращает как идентификатор сессии (ID), имя пользователя (USERNAME)и состояние (Active/Disconnect). Эту команду удобна использовать, когда нужно определить ID RDP сессии пользователя при теневом подключении.

Qwinsta

Список запущенных процессов в конкретной RDP сессии (указывается ID сессии):

qprocess /id:157

qprocess

Логи RDP подключений на клиентах Windows

Также вы можете изучать логи исходящих подключений на стороне RDP клиента. Они доступны в журнале событий Application and Services Logs -> Microsoft -> Windows -> TerminalServices-ClientActiveXCore -> Microsoft-Windows-TerminalServices-RDPClient -> Operation.

Например, событие с Event ID 1102 появляется, когда компьютер устанавливает подключение с удаленным RDS хостом Windows Server или компьютером с Windows 10/11 с включенной службой RDP (десктопные версии Windows также поддерживают несколько одновременных rdp подключений).

The client has initiated a multi-transport connection to the server 192.168.31.102.

событие с ID 1102 в журнале Microsoft-Windows-TerminalServices-RDPClient событие подключения к RDP серверу на клиенте

Следующий RDP скрипт выведет историю RDP подключений на указанном компьютере (для получения событий Event Log используется командлет Get-WinEvent):

$properties = @(
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='LocalUser';e={$_.UserID}}
@{n='Target RDP host';e={$_.Properties[1].Value}}
)
Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-RDPClient/Operational';ID='1102'} | Select-Object $properties

powershell вывести история RDP подключений на клиентском компьютере

Скрипт возвращает SID пользователей, которые инициировали RDP подключения на этом компьютере и DNS имена/IP адреса серверов, к которым подключались пользователи. Вы можете преобразовать SID в имена пользователей.

Также история RDP подключений пользователя хранится в реестре.

В работе системного администратора, нередко возникает необходимость посмотреть логи сервера (Server Logs), с какими задачами работал сервер в конкретное время, какие действия совершали пользователи. Причины возникновения этой необходимости могут быть разные:

  • Сбой в работе сервера;
  • Выявление неблагонамеренных действий;
  • Анализ рабочих процессов.

Всю необходимую информацию можно получить в логи сервера (Server Logs), то есть файлах, в которые вносятся записи о различных процессах, действиях пользователей, и т.п. Но, для этого необходимо понимать, где хранятся эти данные, а главное, как с ними работать.

  • 1 Что такое логи сервера?
  • 2 Как правильно читать логи сервера?
  • 3 Логи серверов на Windows
  • 4 Логи SQL сервера
  • 5 Как включить или выключить запись логов сервера?
  • 6 Где находятся логи сервера?
  • 7 Пример работы с логами сервера
  • 8 Вывод

Что такое логи сервера?

Собственно говоря, само слово «логи сервера», является банальной транслитерацией, от словосочетания «server log», которое переводится как «журнал сервера».

Существуют следующие типы логов:

  • Ошибки – записи, фиксирующие различные сбои в работе сервера, или при обращении к конкретным функциям или задачам. С их помощью можно быстро ликвидировать разные баги и сбои;
  • Доступ – записи, которые фиксируют точные дату и время подключения конкретного пользователя, каким образом он попал на сайт, и т.д. Позволяют проводить аналитическую работу, а также находить уязвимые места, в тех случаях, когда ресурс пытались взломать;
  • Прочее – записи с данными о работе разных компонентов сервера, например, почты.

Разумеется, если вы не наблюдаете никаких проблем, или подозрительных моментов, связанных с работой сервера, то нет никакой необходимости в частом просмотре логов. Тем не менее, специалисты рекомендуют выборочно изучать их, хотя бы раз в год.

С другой стороны, если уже произошло какое-то ЧП, например, сайт резко начал выдавать большое количество ошибок, подвергся спам-атаке, или стремительно возросла нагрузка на сервер, то изучение логов, позволит быстро понять в чем проблема и устранить её.

Тем не менее, для большинства рядовых пользователей записи в log-файлах, представляют собой просто странный набор символов. А значит, нужно понять, как правильно их читать.

Как правильно читать логи сервера?

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

Итак, запись лога доступа, из файла access.log:

mysite.biz 25.34.94.132 — — [21/Nov/2017:03:21:08 +0200] «GET /blog/2/ HTTP/1.0» 200 18432 «-» «Unknow Bot (http://www.unknow.com/bot; [email protected])»

Что она обозначает:

  • mysite.biz – домен сайта, которым вы интересуетесь;
  • 34.94.132 – IP-адрес, который использовал пользователь при заходе на сайт;
  • [21/Nov/2017:03:21:08 +0200] – дата, точное время и часовой пояс пользователя;
  • GET – запрос, который отправляется для получения данных. В том случае, если пользователь передает данные, запрос будет «POST»;
  • /blog/2/ — относительный адрес страницы, к которой был обращен запрос;
  • HTTP/1.0 – используемый протокол;
  • 200 – код ответа на запрос;
  • 18432 – количество данных, переданных по запросу, в байтах;
  • Unknow Bot (http://www.unknow.com/bot; [email protected]) – данные о роботе, или реальном человеке, который зашел на сайт. В том случае, если это человек, будет отображена ОС, тип устройства и т.д. В конкретном примере на сайт зашел робот-парсер, принадлежащий ресурсу unknow.com.

Таким образом, мы узнали, что с IP-адреса 25.34.94.132, двадцать первого ноября, 2017-го года, в три часа, двадцать одну минуту и восемь секунд, на наш сайт заходил бот, принадлежащий другому веб-ресурсу. Он отправил запрос на получение данных, и получил 18432 байт информации.

Теперь можно заблокировать доступ для ботов от этого сайта, либо от всех, кто пользуется этим IP, разумеется, если в этом есть необходимость.

Логи ошибок, можно посмотреть в файле с говорящим именем – error.log. Они выглядят следующим образом:

[Sat Oct 1 18:23:28.719615 2019] [:error] [pid 10706] [client 44.248.44.22:35877]

PHP Notice: Undefined variable: moduleclass_sfx in

/var/data/www/mysite.biz/modules/contacts/default.php on line 13

Что здесь написано?

  1. Дата, время и тип ошибки, а также IP-адрес, который использовал посетитель;
  2. Тип события, в данном случае – «PHP Notice» (уведомление), а также уточнение, что в данном случае, мы имеем дело с неизвестной переменной;
  3. Местоположение файла с уведомлением, а также строка, на которой оно находится.

Если говорить просто, то в данном случае мы имеем сообщение о том, что первого октября, в 18:23, 2019-го года, произошла ошибка, связанная с модулем контактов.

Разумеется, даже после расшифровки, полученные данные не так просто проанализировать. Именно поэтому, для удобной обработки данных из логов сервера, используется различное программное обеспечение. К таким программам относятся: Awstats, Webtrends, WebAlyzer, и многие другие.

Сегодня существует множество платных и бесплатных вариантов программ, для обработки и анализа лог-файлов.

У логов серверов на Windows, изначально более удобный и структурированный вывод информации, в виде простой и понятной таблицы.

Существует несколько уровней событий:

  • Подробности;
  • Сведения;
  • Предупреждение;
  • Ошибка;
  • Критический.

Также есть возможность быстрой фильтрации и сортировки записей, в зависимости от того, какие данные вы хотите получить.

Логи SQL сервера

На сегодняшний день, базы данных SQL, являются наиболее распространенным способом работы с большими объемами информации. В первую очередь, логи sql сервера, стоит изучить, если вы не уверены в том, что какие-то процессы были успешно завершены. Этими процессами могут быть:

  • Резервное копирование;
  • Восстановление данных;
  • Массовые изменения;
  • Различные скрипты, и программы для обработки данных.

Для того, чтобы просмотреть записи в логах, можно использовать SQL Server Management Studio, либо другой, удобный вам редактор текстов. Записи распределены по журналам следующих типов:

  • Сбор данных;
  • Database Mail;
  • SQL Сервер;
  • События Windows;
  • Журнал заданий;
  • Коллекция аудита;
  • SQL Сервер, агент.

Для того, чтобы получить доступ к журналам, необходимо иметь права «securityadmin».

Как включить или выключить запись логов сервера?

Для того, чтобы осуществить эту операцию, нужно зайти в административную панель вашего хостера. Как правило, в основном меню есть раздел «Журнал», или «Логи», в котором можно включить или выключить запись данных о предоставленном доступе, ошибках, и т.п.

Где находятся логи сервера?

Расположение журналов, зависит в первую очередь от используемой вами операционной системы.

Логи серверов с CentOS, или Fedora, хранятся в дирректории «/var/log/».

Названия файлов:

  • Журнал ошибок – «error.log»;
  • Журнал nginx – «nginx»;
  • Журнал доступов – «log»;
  • Основной журнал – «syslog»;
  • Журнал загрузки системы – «dmesg».

Логи ошибок, связанных с работой MySQL, находятся в директории «/var/lib/mysql/», в файле «$hostname.err».

Для операционных систем Debian и Ubuntu, логи сервера располагаются в папке «/var/log/», в файлах:

  • Nginx — журнал nginx;
  • /mysql/error.log – журнал ошибок для баз данных MySQL;
  • Syslog – основной журнал;
  • Dmesg – загрузка системы, драйвера;
  • Apache2 – журнал веб-сервера Apache.

Как видите, у всех ОС, основанных на Linux, логи сервера, как правило имеют одинаковые названия, и директории.

С логами для Windows server, дело обстоит несколько иначе. Если нужно просмотреть журналы, необходимо войти в систему, нажать клавиши «Win» и «R», после чего откроется окно просмотра событий, где есть возможность подобрать интересующие нас логи.

Если вы хотите посмотреть логи PowerShell, то необходимо открыть программу и ввести команду: «Get-EventLog -Logname ‘System’».

Все данные будут выведены в виде удобной таблицы.

Пример работы с логами сервера

Представьте себе, что вы внезапно обнаружили существенное увеличение нагрузки на ваш сервер, связанное с внешними воздействиями. Сервисы аналитики начинают регистрировать рекорды посещаемости, и можно было бы радоваться, но видно, что эти «пользователи» не совершают действий, которых от них ждут, неважно что это – изучение контента, или покупки на сайте.

Можно потратить много времени на выяснения причины, а можно просто посмотреть логи доступа и проверить, с каких IP, и кто заходил на ваш сайт, в выбранные промежуток времени. Вполне вероятно, что вы обнаружите большое количество переходов с нескольких IP-адресов, которые делались автоматически, то есть ваш сайт попал под DDoS-атаку.

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

Вывод

На сегодняшний день, log-файлы сервера, являются крайне удобным инструментом, который позволяет отслеживать работу сайта, выявлять баги и ошибки, злонамеренных пользователей, противодействовать DDoS-атакам.

Для того, чтобы правильно работать с логами сервера, необходимо знать их расположение, иметь возможность изучить нужные файлы, а также понимать разные типы записей. В большинстве панелей управления, пользователю сразу предоставляется возможность включать и выключать запись логов. К тому же есть возможность скачивать или просматривать журналы.

Кроме того, сегодня можно найти ряд программного обеспечения, и они позволяют взаимодействовать с информацией из журналов через удобный графический интерфейс, с большой скоростью расшифровывать её и выводить в простом виде.

У систем, основанных на Linux, как правило примерно одинаковое расположение файлов с логами, что существенно упрощает работу с ними.

У Windows Server, есть свой собственный графический интерфейс для чтения логов, который весьма удобен, и позволяет быстро получить необходимую информацию.

Загрузка…

Hi,

Thank you for posting in forum!

As I understand, you want to check the IP addresses that your
computer has entered or accessed. If misunderstand, please let me know.

There are three methods to check the Incoming/Outgoing connection
information.

1.Windows Firewall can log any ingoing/outgoing activity.This
will 
need
to open Windows 12’s Windows Firewall with Advanced Security feature first.

The log will show below:

For more details about Windows Firewall Log, please refer to the following link:
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc758040(v=ws.10)?redirectedfrom=MSDN

To open the log please refer the following steps:

 1)Press Win+R,
type 
wf.msc, and press Enter. The targeted window will pops open.

 2)Then, click Properties link
on the right side of the screen. 

 3)Click Customize… button
in the Logging section. In the dialog box that pops up, specify where you want to save the log file, the maximum log size, and whether to log dropped packets and successful connections.

 4)Back to the main Windows Firewall and Advanced
Security
 window. Click Monitoring on the left side panel, locate the Logging Settings section in the middle
side of panel, and click the file link for the log file.

 5)The log will open in Notepad automatically.

2.If you need more details about incoming and outgoing network connections information,
you could use MS Network Monitor. Here is the download link:

https://www.microsoft.com/en-us/download/details.aspx?id=4865

3.You can use the cmd command: netstat to choose which command
you need.

You could refer to the following official article as your reference:

https://www.wikihow.com/See-Active-Network-Connections-(Windows)

Please Note: Since the web site is not hosted by Microsoft, the link may change
without notice. Microsoft does not guarantee the accuracy of this information.

Hope this can help you, if you have anything unclear, please
let me know.

Best Regards,

Ellen

Please remember to mark the replies as answers if they help and
unmark them if they provide no help.
If you have feedback for TechNet Subscriber Support, contact
tnmff@microsoft.com.

  • Edited by

    Friday, September 27, 2019 9:41 AM

  • Proposed as answer by
    Ellen ZhuMicrosoft contingent staff
    Friday, October 4, 2019 1:42 AM

Как посмотреть журнал ошибок ОС Windows 2012

Просмотр системного журнала

Если в работе Windows 2012 появляется какая-то нестабильность, или появляются ошибки запуска\установки приложений, то это может быть связано с появлениями ошибок в самой операционной системе.

Все системные ошибки и предупреждения можно найти в «Журнале системы«.

В нем сохраняется информация о событиях, записываемых системными компонентами Windows.

Для просмотра и сохранения системного журнала нужно выполнить шаги:

Открыть «Пуск«:

Открыть «Панель управления«:

В «Панели управления» выбрать «Просмотр журналов событий«

В открывшемся окне выбрать «Просмотр событий» -> «Журналы Windows» -> «Система«

Экспорт журнала

Системный журнал в полном объеме можно выгрузить путем нажатия на ссылку «Сохранить все события как. «

После нажатия ссылки «Сохранить все события как. » нужно выбрать путь и имя файла для сохраняемого журнала.

При сохранении файла возможно появление окна «Отображение сведений«.

В данном окне нужно выбрать пункт «Отображать сведения для следуюших языков: Русский«

Источник

Журналы Windows

Операционная система Windows, системные службы и приложения записывают события и ошибки в системные журналы, чтобы в дальнейшем у системного администратора была возможность проверки операционной системы и диагностики проблем.

Получить доступ к этим записям можно через встроенное приложение Просмотр событий (Event Viewer). Есть несколько вариантов запуска данного приложения:

  • через меню Пуск – Средства администрирования Windows – >Просмотр событий (Start – Windows Administrative Tools – Event Viewer);
  • в командной строке или в окне Выполнить набрать eventvwr.msc:

В Диспетчере серверов в разделе Средства выбрать Просмотр событий (Server Manager – Tools – Event Viewer):

Описание интерфейса программы

Окно программы состоит из следующих компонентов:

Скриншот №3. Интерфейс программы

  • Панель навигации позволяет выбрать конкретный журнал, записи которого необходимо просмотреть;
  • Список событий, содержащийся в выбранном журнале. В колонках выведена базовая информация о событии. Их можно отсортировать по датам, типам, категориям событий и т.д.;
  • Детальная информация о выбранном во второй панели событии. Также детальную информацию можно открыть в отдельном окне, если кликнуть по нужному событию два раза;
  • Панель быстрых действий, которые можно совершить с данным журналом или событием. Действия также доступны в контекстном меню (клик правой кнопкой мыши по журналу или событию).

Для удобства просмотра и управления системные журналы разбиты по категориям:

  • Приложения (Application) – как и гласит название, содержит события и ошибки приложений;
  • Безопасность (Security) – если в операционной системе включена и настроена функция аудита, журнал будет содержать записи, связанные с отслеживанием соответствующих событий (например, авторизация пользователя или попытки неудачного входа в операционную систему);
  • Система (System) – здесь регистрируются события операционной системы и системных сервисов;
  • Установка (Setup) – события, связанные с инсталляцией обновлений Windows, дополнительных приложений.

В разделе Журналы приложений и служб (Applications and Services Logs) можно найти более детальную информацию о событиях отдельных служб и приложений, зарегистрированных в операционной системе, что бывает полезно при диагностике проблем в работе отдельных сервисов.

Сами события также разделяются на типы:

  • Сведения (Information) — информируют о штатной работе приложений.
  • Предупреждение (Warning) — событие, свидетельствующее о возможных проблемах в будущем (например, заканчивается свободное место на диске – приложения могут продолжать работу в штатном режиме, но когда место закончится совсем, работа будет невозможна).
  • Ошибка (Error) — проблема, ведущая к деградации приложения или службы, потерям данных.
  • Критическое (Critical) — значительная проблема, ведущая к неработоспособности приложения или службы.
  • Аудит успеха (Success audit) — событие журнала Безопасность (Security), обозначающее успешно осуществленное действие, для которого включено отслеживание (например, успешный вход в систему).
  • Аудит отказа (Failure audit) — событие журнала Безопасность (Security) обозначающее безуспешную попытку осуществить действие, для которого включено отслеживание (например, ошибка входа в систему).

Работа с журналами

Службы и приложения могут генерировать огромное количество самых разнообразных событий. Для простоты доступа к нужным записям журнала можно использовать функцию фильтрации журнала:

Правый клик по журналу – Фильтр текущего журнала… (>Filter Current Log…), либо выбрать данную функцию в панели быстрых действий. Открывшееся окно позволяет настроить фильтр и отобразить только те события, которые необходимы в данный момент:

Можно задать временной период, уровни события, выбрать журналы и конкретные источники событий. Если известны коды событий, которые нужно включить или исключить из фильтра, их также можно указать.

Когда необходимость в фильтрации событий отпадет, ее можно отключить действием Очистить фильтр (Clear Filter):

Приложение Просмотр событий (Event Viewer) позволяет также настроить дополнительные свойства журналов. Доступ к настройкам можно получить через панель быстрых действий, либо через контекстное меню журнала – правый клик по журналу – Свойства (Properties):

В открывшемся окне настроек можно увидеть путь, по которому сохраняется файл журнала, текущий размер, а также можно задать максимальный размер файла:

В нижней части окна можно выбрать вариант действия при достижении журналом максимального значения:

  • Переписывать события при необходимости (Overwrite events as needed) – новое событие будет записываться поверх самого старого события в журнале, таким образом будут доступны события только за определенный диапазон времени.
  • Архивировать журнал при заполнении (Overwrite the log when full) – заполненный журнал будет сохранен, последующие события будут записываться в новый файл журнала. При необходимости доступа к старым событиям, архивный файл можно будет открыть в приложении Просмотр событий (Event Viewer).
  • Не переписывать события (Do not overwrite events) – при заполнении журнала выдается системное сообщение о необходимости очистить журнал, старые события не перезаписываются.

Источник

Управление ведением журнала доступа пользователей Manage User Access Logging

Область применения. Windows Server (Semi-Annual Channel), Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 Applies To: Windows Server (Semi-Annual Channel), Windows Server 2016, Windows Server 2012 R2, Windows Server 2012

В этом документе описываются принципы управления ведением журнала доступа пользователей (UAL). This document describes how to manage User Access Logging (UAL).

Ведение журнала доступа пользователей (UAL) — это компонент, который помогает администраторам сервера подсчитать количество уникальных клиентских запросов ролей и служб на локальном сервере. UAL is a feature that can help server administrators quantify the number of unique client requests of roles and services on a local server.

UAL установлен и включен по умолчанию и выполняет сбор данных в режиме, практически приближенном к реальному времени. UAL is installed and enabled by default and collects data on a nearly real-time basis. Существует всего несколько параметров конфигурации для UAL. There are only a few configuration options for UAL. Данный документ описывает эти параметры и их назначение. This document describes these options and their intended purpose.

Дополнительные сведения о преимуществах UAL см. в статье Приступая к работе с журналом доступа пользователей. To learn more about the benefits of UAL, see the Get Started with User Access Logging.

Содержание документа In this document

Параметры конфигурации, описываемые в данном документе, включают в себя следующее: The configuration options covered in this document include:

Отключение и включение службы UAL Disabling and enabling the UAL service

Сбор и удаление данных Collecting and removing data

Удаление данных, записанных службой UAL Deleting data logged by UAL

Управление UAL в крупномасштабных средах Managing UAL in high volume environments

Восстановление из ошибочного состояния Recovering from a corrupt state

Включение отслеживания использования лицензий рабочих папок Enable Work Folders usage license tracking

Отключение и включение службы UAL Disabling and enabling the UAL service

UAL включается и запускается по умолчанию, когда компьютер под управлением Windows Server 2012 или более поздней версии устанавливается и запускается впервые. UAL is enabled and runs by default when a computer running Windows Server 2012, or later, is installed and started for the first time. Для удовлетворения требований конфиденциальности или других рабочих нужд администратору может понадобиться отключить или запретить работу UAL. Administrators may want to turn off and disable UAL to comply with privacy requirements or other operational needs. Можно отключить UAL с помощью консоли служб, из командной строки или с помощью командлетов PowerShell. You can turn off UAL using the Services console, from the command line, or by using PowerShell cmdlets. Однако, чтобы гарантировать, что UAL не будет запускаться снова при следующем запуске компьютера, необходимо также отключить службу. However, to ensure that UAL does not run again the next time the computer is started, you also need to disable the service. В следующих процедурах описывается отключение и отключение UAL. The following procedures describes how to turn off and disable UAL.

Для получения информации о службе UAL, включая сведения о том, работает или приостановлена служба, включена она или отключена, можно использовать командлет Get-Service UALSVC PowerShell. You can use the Get-Service UALSVC PowerShell cmdlet to retrieve information about the UAL Service including whether it is running or stopped and whether it is enabled or disabled.

Остановка и отключение службы UAL через консоль службы To stop and disable the UAL service by using the Services console

Выполните вход на сервер с помощью учетной записи с правами локального администратора. Sign in to the server with an account that has local administrator privileges.

В диспетчере серверов выберите Средства, затем щелкните Службы. In Server Manager, point to Tools, and then click Services.

Прокрутите вниз и выберите пункт Служба ведения журнала доступа пользователей. Щелкните Остановка службы. Scroll down and select User Access Logging Service.Click Stop the service.

Щелкните правой кнопкой мыши — имя службы и выберите пункт свойства. Right-click the service name and select Properties. На вкладке Общие поменяйте Тип запуска на Отключено и нажмите кнопку ОК. On the General tab, change the Startup type to Disabled, and then click OK.

Остановка и отключение UAL из командной строки To stop and disable UAL from the command line

Выполните вход на сервер с помощью учетной записи с правами локального администратора. Sign in to the server with an account that has local administrator privileges.

Нажмите клавишу с эмблемой Windows + R, а затем введите cmd, чтобы открыть окно командной строки. Press the Windows logo + R, then type cmd to open a Command Prompt window.

Если появится диалоговое окно контроля учетных записей, подтвердите, что отображаемое в нем действие именно то, которое требуется, и нажмите кнопку Да. If the User Account Control dialog box appears, confirm that the action it displays is what you want, and then click Yes.

Введите net stop ualsvc и нажмите клавишу ВВОД. Type net stop ualsvc, and then press ENTER.

Введите netsh ualsvc set opmode mode=disable и нажмите клавишу ВВОД. Type netsh ualsvc set opmode mode=disable, and then press ENTER.

Следующие командлеты Windows PowerShell выполняют ту же функцию, что и предыдущая процедура. The following Windows PowerShell cmdlet or cmdlets perform the same function as the preceding procedure. Вводите каждый командлет в одной строке, несмотря на то, что здесь они могут отображаться разбитыми на несколько строк из-за ограничений форматирования. Enter each cmdlet on a single line, even though they may appear word-wrapped across several lines here because of formatting constraints.

Также остановить и отключить UAL можно с помощью команд Windows PowerShell: Stop-service и Disable-Ual. You can also stop and disable UAL by using the Stop-service and Disable-Ual Windows PowerShell commands.

Если позднее вы хотите перезапустить и снова включить UAL, это можно сделать с помощью следующих процедур. If at a later date you want to restart and re-enable UAL you can do so with the following procedures.

Запуск и включение службы UAL через консоль служб To start and enable the UAL service by using the Services console

Выполните вход на сервер с помощью учетной записи с правами локального администратора. Sign in to the server an account that has local administrator privileges.

В диспетчере серверов выберите Средства, затем щелкните Службы. In Server Manager, point to Tools, and then click Services.

Прокрутите вниз и выберите пункт Служба ведения журнала доступа пользователей. Щелкните Запуск службы. Scroll down and select User Access Logging Service.Click Start the service.

Правой кнопкой мыши щелкните имя службы и выберите Свойства. Right-click the service name and select Properties. На вкладке Общие поменяйте Тип запуска на Автоматически и нажмите кнопку ОК. On the General tab, change the Startup type to Automatic, and then click OK.

Запуск и включение UAL из командной строки To start and enable UAL from the command line

Выполните вход на сервер с помощью учетной записи локального администратора. Sign in to the server with local administrator credentials.

Нажмите клавишу с эмблемой Windows + R, а затем введите cmd, чтобы открыть окно командной строки. Press the Windows logo + R, then type cmd to open a Command Prompt window.

Если появится диалоговое окно контроля учетных записей, подтвердите, что отображаемое в нем действие именно то, которое требуется, и нажмите кнопку Да. If the User Account Control dialog box appears, confirm that the action it displays is what you want, and then click Yes.

Введите net start ualsvc и нажмите клавишу ВВОД. Type net start ualsvc, and then press ENTER.

Введите netsh ualsvc set opmode mode=enable и нажмите клавишу ВВОД. Type netsh ualsvc set opmode mode=enable, and then press ENTER.

Следующие командлеты Windows PowerShell выполняют ту же функцию, что и предыдущая процедура. The following Windows PowerShell cmdlet or cmdlets perform the same function as the preceding procedure. Вводите каждый командлет в одной строке, несмотря на то, что здесь они могут отображаться разбитыми на несколько строк из-за ограничений форматирования. Enter each cmdlet on a single line, even though they may appear word-wrapped across several lines here because of formatting constraints.

Также запустить и вновь включить UAL можно с помощью команд Windows PowerShell: Start-service и Enable-Ual. You can also start and reenable UAL by using the Start-service and Enable-Ual Windows PowerShell commands.

Сбор данных UAL Collecting UAL data

В дополнение к командлетам PowerShell, описанным в предыдущем разделе, для получения данных UAL можно использовать 12 дополнительных командлетов: In addition to the PowerShell cmdlets described in the previous section, 12 additional cmdlets can be used to collect UAL data:

Get-UalOverview: предоставляет сведения, относящиеся к UAL, а также журнал установленных продуктов и ролей. Get-UalOverview: Provides UAL related details and history of installed products and roles.

Get-UalServerUser: предоставляет данные о доступе пользователя клиента на локальный или целевой сервер. Get-UalServerUser: Provides client user access data for the local or targeted server.

Get-UalServerDevice: предоставляет данные о доступе устройства клиента на локальный или целевой сервер. Get-UalServerDevice: Provides client device access data for the local or targeted server.

Get-UalUserAccess: предоставляет данные о доступе пользователя клиента к каждой роли или продукту, установленным на локальном или целевом сервере. Get-UalUserAccess: Provides client user access data for each role or product installed on the local or targeted server.

Get-UalDeviceAccess: предоставляет данные о доступе устройства клиента к каждой роли или продукту, установленным на локальном или целевом сервере. Get-UalDeviceAccess: Provides client device access data for each role or product installed on the local or targeted server.

Get-UalDailyUserAccess: предоставляет данные о доступе пользователя клиента за каждый день года. Get-UalDailyUserAccess: Provides client user access data for each day of the year.

Get-UalDailyDeviceAccess: предоставляет данные о доступе устройства клиента за каждый день года. Get-UalDailyDeviceAccess: Provides client device access data for each day of the year.

Get-UalDailyAccess: предоставляет данные о доступе как пользователя, так и устройства клиента за каждый день года. Get-UalDailyAccess: Provides both client device and user access data for each day of the year.

Get-UalHyperV: предоставляет данные о виртуальной машине, относящиеся к локальному или целевому серверу. Get-UalHyperV: Provides virtual machine data relevant to the local or targeted server.

Get-UalDns: предоставляет специальные данные DNS-клиента локального или целевого DNS-сервера. Get-UalDns: Provides DNS client specific data of the local or targeted DNS server.

Get-UalSystemId: предоставляет специальные системные данные для уникальной идентификации локального или целевого сервера. Get-UalSystemId: Provides system specific data to uniquely identify the local or targeted server.

Get-UalSystemId предназначен для того, чтобы предоставлять уникальный профиль сервера всем остальным данным с этого сервера для проведения сопоставления с ним. Get-UalSystemId is meant to provide a unique profile of a server for all other data from that server to be correlated with. Если в одном из параметров нового профиля создается сервер, в котором возникают какие-либо изменения в Get-UalSystemId . Get-UalOverview If a server experiences any change in the in one of the parameters of Get-UalSystemId a new profile is created. Get-UalOverview предназначен для того, чтобы предоставлять администратору список установленных и используемых на сервере ролей. is meant to provide the administrator with a list of roles installed and being used on the server.

Основные возможности службы печати и документов и файловых служб устанавливаются по умолчанию. Basic features of Print and Document Services and File Services are installed by default. Поэтому администраторы могут всегда видеть информацию по этим службам, как при установленных полных ролях. Therefore administrators can expect to always see information on these displayed as if the full roles are installed. Отдельные командлеты UAL входят в состав Hyper-V и службы DNS из-за уникальных данных, которые UAL собирает для этих ролей сервера. Separate UAL cmdlets are included for Hyper-V and DNS because of the unique data that UAL collects for these server roles.

Вариант сценария обычного использования командлетов UAL мог бы быть таким: администратор запрашивает у UAL уникальные клиентские доступы за определенный диапазон дат. A typical use case scenario for UAL cmdlets would be for an administrator to query UAL for unique client accesses over the course of a date range. Это можно сделать несколькими способами. This can be done in a variety of ways. Далее приводится рекомендуемый метод запроса уникальных доступов устройств за диапазон дат. The following is a recommended method to query unique device accesses over a date range.

Он возвращает подробный список всех уникальных клиентских устройств по IP-адресам, которые совершали запросы к серверу в этот диапазон дат. This will return a verbose listing of all unique client devices, by IP address, that have made requests of the server in that date range.

Значение «Активитикаунт» для каждого уникального клиента ограничено 65 535 в день. ‘ActivityCount’ for each unique client is limited to 65,535 per day. Вызов WMI из PowerShell также необходим только при запросе по дате. Also, calling into WMI from PowerShell is only required when you query by date. Все остальные параметры командлета UAL могут использоваться в рамках запросов PowerShell, как в следующем примере: All other UAL cmdlet parameters can be used within PS queries as expected, as in the following example:

UAL позволяет хранить историю в течение двух лет. UAL retains up to two years’ worth of history. Чтобы разрешить получение данных UAL администратором при запуске службы, UAL создает копию активного файла базы данных Current. mdb в файле с именем GUID. mdb каждые 24 часа для использования поставщиком WMI. To allow retrieval of UAL data by an administrator when the service is running, UAL makes a copy of the active database file, current.mdb, to a file named GUID.mdb every 24 hours for the WMI provider’s use.

В первый день года UAL создает новый GUID.mdb. On the first day of the year, UAL will create a new GUID.mdb. Старый GUID. mdb сохраняется в качестве архива для использования поставщиком. The old GUID.mdb is retained as an archive for the provider’s use. По прошествии двух лет исходный GUID.mdb будет перезаписан. After two years, the original GUID.mdb will be overwritten.

Следующая процедура должна выполняться только опытным пользователем или разработчиком, тестирующими свой собственный инструментарий интерфейсов программирования приложений UAL. The following procedure should be performed only by an advanced user and would commonly be used by a developer testing their own instrumentation of UAL application programming interfaces.

Настройка 24-часового интервала по умолчанию так, чтобы данные стали видимы поставщику WMI To adjust the default 24-hour interval to make data visible to the WMI provider

Выполните вход на сервер с помощью учетной записи с правами локального администратора. Sign in to the server with an account that has local administrator privileges.

Нажмите клавишу с эмблемой Windows + R, а затем введите cmd, чтобы открыть окно командной строки. Press the Windows logo + R, then type cmd to open a Command Prompt window.

Добавьте значение реестра: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\WMI\AutoLogger\Sum\PollingInterval (REG_DWORD). Add the registry value: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\WMI\AutoLogger\Sum\PollingInterval (REG_DWORD).

Неправильное изменение реестра может серьезно повредить систему. Incorrectly editing the registry may severely damage your system. Перед внесением изменений в реестр следует сделать резервную копию всех ценных данных на компьютере. Before making changes to the registry, you should back up any valued data on your computer.

В следующем примере показано, как добавить интервал в два минуты (не рекомендуется в долгосрочном состоянии выполнения): reg Add Хклм\систем\куррентконтролсет\контрол\вми \ Аутологжер\сум/v POLLINGINTERVAL/T REG _ DWORD/d 120000/f The following example shows how to add a two-minute interval (not recommended as a long term running state): REG ADD HKLM\System\CurrentControlSet\Control\WMI\AutoLogger\Sum /v PollingInterval /t REG_DWORD /d 120000 /F

Единица измерения времени — миллисекунды. Time values are in milliseconds. Минимальное значение — 60 секунд, максимальное — семь дней, а значение по умолчанию — 24 часа. The minimum value is 60 seconds, the maximum is seven days, and the default is 24 hours.

Для остановки и перезапуска службы ведения журнала доступа пользователей используйте консоль служб. Use the Services console to stop and restart the User Access Logging Service.

Удаление данных, записанных службой UAL Deleting data logged by UAL

Служба UAL не задумывалась как компонент для решения критически важных задач. UAL is not intended to be a mission critical component. Данная служба спроектирована так, чтобы как можно меньше воздействовать на работу локальной системы и при этом обеспечивать высокий уровень надежности. Its design is intended to impact local system operations as little as possible while maintaining a high level of reliability. Это также позволяет администратору вручную удалить базу данных UAL и вспомогательные файлы (каждый файл в каталоге \Windows\System32\LogFilesSUM) в соответствии с рабочими потребностями. This also allows the administrator to manually delete UAL database and supporting files (every file in \Windows\System32\LogFilesSUM\ directory) to meet operational needs.

Удаление данных, записанных службой UAL To delete data logged by UAL

Остановите службу ведения журнала доступа пользователей. Stop the User Access Logging Service.

Откройте проводник. Open Windows Explorer.

Перейдите по адресу **\Windows\System32\Logfiles\SUM \ **. Go to \Windows\System32\Logfiles\SUM\.

Удалите все файлы из этой папки. Delete all files in the folder.

Управление UAL в крупномасштабных средах Managing UAL in high volume environments

В данном разделе описывается, что может ожидать администратор, когда UAL используется на сервере с большим количеством клиентов. This section describes what an administrator can expect when UAL is used on a server with high client volume:

Максимальное количество доступов, которое может быть записано UAL, составляет 65 535 в день. The maximum number of accesses that can be recorded with UAL is 65,535 per day. UAL не рекомендуется использовать на серверах, которые подключены непосредственно к Интернету, таких как веб-серверы, напрямую подключенные к Интернету, или в тех случаях, когда предельно высокая производительность является основной функцией сервера (например, в средах с рабочими нагрузками высокопроизводительных вычислений). UAL is not recommended for use on servers that are connected directly to the Internet, such as web servers that are connected directly to the Internet, or in scenarios where extremely high performance is the primary function of the server (such as in HPC workload environments). В основном он предназначен для малых, средних и корпоративных интрасетей, в которых предполагается наличие большого объема данных, но не так высокое, как и многие из развертываний, которые регулярно обслуживают объем трафика в Интернете. UAL is primarily intended for small, medium, and enterprise intranet scenarios where high volume is expected, but not as high as many deployment that serve Internet-facing traffic volume on a regular basis.

UAL в памяти: так как в UAL используется расширяемая подсистема хранилища (ESE), требования к памяти UAL увеличиваются со временем (или по количеству клиентских запросов). UAL in Memory: Because UAL uses the Extensible Storage Engine (ESE), UAL’s memory requirements will increase over time (or by quantity of client requests). Но память будет освобождаться, поскольку это необходимо системе для минимизации воздействия на производительность. But memory will be relinquished as the system requires it to minimize impact on system performance.

UAL на диске. требования к жесткому диску для жестких дисков необходимы примерно так, как показано ниже: UAL on Disk: UAL’s hard disk requirements are approximately as shown below:

0 уникальных клиентских записей: 22 МБ 0 unique client records: 22M

50 000 уникальных клиентских записей: 80 МБ 50,000 unique client records: 80 M

500 000 уникальных клиентских записей: 384 МБ 500,000 unique client records: 384M

1 000 000 уникальных клиентских записей: 729 МБ 1,000,000 unique client records: 729M

Восстановление из ошибочного состояния Recovering from a corrupt state

В этом разделе обсуждается использование расширяемого механизма хранилища (ESE) на высоком уровне, а также действия администратора в случае повреждения или восстановления данных UAL. This section discusses UAL’s use of the Extensible Storage Engine (ESE) at a high level and what an administrator can do if UAL data is corrupted or unrecoverable.

Служба UAL использует ESE для оптимизации использования системных ресурсов и обеспечения их устойчивости к повреждению. UAL uses ESE to optimize use of system resources and for its resistance to corruption. Дополнительные сведения о преимуществах ESE см. в разделе Расширяемый обработчик хранилищ в MSDN. For more information about the benefits of ESE, see Extensible Storage Engine on MSDN.

При каждом запуске службы UAL обработчик ESE выполняет «мягкое» восстановление. Each time the UAL service starts ESE performs a soft recovery. Дополнительные сведения см. в разделе Файлы расширяемого обработчика хранилищ в MSDN. For more information, see Extensible Storage Engine Files on MSDN.

Если выполнить «мягкое» восстановление будет проблематично, то ESE выполнит восстановление после сбоя. If there is a problem with the soft recovery, ESE will perform a crash recovery. Дополнительные сведения см. в разделе Функция JetInit в MSDN. For more information, see JetInit Function on MSDN.

Если UAL все же не может запуститься с существующим набором файлов ESE, то все файлы в каталоге \Windows\System32\LogFiles\SUM\ будут удалены. If UAL is still unable to start with the existing set of ESE files, it will delete all files in the \Windows\System32\LogFiles\SUM\ directory. После удаления этих файлов будет вновь запущена служба ведения журнала доступа пользователей и созданы новые файлы. After these files are deleted, the User Access Logging Service will restart and new files are created. В этом случае служба UAL продолжит работу, как если бы она функционировала на вновь установленном компьютере. The UAL service will then resume as if on a freshly installed computer.

Файлы в каталоге базы данных UAL никогда не должны перемещаться или изменяться. The files in UAL database directory should never be moved or modified. Если это случится, то будут инициированы действия по восстановлению, включая процедуру очистки, описанную в данном разделе. Doing so will initiate the recovery steps, including the cleanup routine described in this section. Если требуются резервные копии каталога \Windows\System32\LogFiles\SUM, то необходимо архивировать каждый файл из этого каталога, чтобы стала возможной операция восстановления. If backups of the\Windows\System32\LogFiles\SUM\ directory are needed, then every file in this directory must be backed up together in order for a restore operation to function as expected.

Включение отслеживания использования лицензий рабочих папок Enable Work Folders usage license tracking

Сервер рабочих папок может использовать UAL для отчета по использованию клиента. Work Folders server can use UAL to report client usage. В отличие от UAL, ведение журнала рабочих папок не включено по умолчанию. Unlike UAL, Work Folder logging is not turned on by default. Вы можете включить его, изменив следующий раздел реестра: You can enable it with the following regkey change:

После добавления этого раздела реестра необходимо перезапустить службу SyncShareSvc на сервере, чтобы включить ведение журнала. After the regkey is added, you must restart the SyncShareSvc service on the server, to enable logging.

После включения ведения журнала 2 информационных события регистрируются в канал Windows Logs\Application каждый раз, когда клиент подключается к серверу. After logging is enabled, 2 informational events get logged to the Windows Logs\Application channel each time a client connects to the server. Для рабочих папок каждый пользователь может иметь одно или несколько клиентских устройств, которые подключаются к серверу проверяют наличие обновлений данных каждые 10 минут. For Work Folders, each user may have one or more client devices that connect to the server and check for data updates every 10 minutes. Если с сервером взаимодействует 1000 пользователей, каждый из которых имеет 2 устройства, журналы приложений будут перезаписываться каждые 70 минут, что затрудняет устранение независимых проблем. If the server is experiencing 1000 users, each with 2 devices the application logs will overwrite every 70 minutes, making troubleshooting unrelated issues difficult. Чтобы избежать этого, можно временно отключить службу ведения журнала доступа пользователей или увеличить размер канала Логс\аппликатион на сервере Windows. To avoid this, you can disable the User Access Logging service temporarily, or increase the size of the server’s Windows Logs\Application channel.

Источник

How to check Windows server logs (Windows Event Log Types. Microsoft Windows Server is an operating system that provides network administrators with a collection of enterprise level management features. Accordingly, some of these features include data storage, applications, security, network, and hardware management.

Similarly, Microsoft’s collection of desktop operating systems allow you to view event logs through a set of Administrative Tools. So, Windows Server offers similar features but in a more enterprise capacity. After all, event logging and tracing are important parts of running servers. Thus, this guide will explore how you can find Windows server logs and how to interpret the information from them.

Shall we start with How to check Windows server logs (Windows Event Log Types).

Understanding The Windows Event Log

How to check Windows server logs (Windows Event Log Types Explained)

If your servers are positioned in a fairly medium or large company, they may be collecting thousands of events hourly. Especially if you have not configured your Windows Server Event Logs. Basically, the event log is separated into channels. The four most important are:

  • System: Features events related to system software and/or hardware. For instance, driver failures or installations.
  • Application: Contains events logged by (mostly) Windows applications.
  • Security: Contains events pertaining to the security of the Windows system. This may include failed login attempts.
  • Setup: Features system related event logs for setups and updates. For instance, Windows updates.

Besides, Microsoft also has channels for its features such as BitLocker, AppLocker, and Windows Firewall. Additionally, the event log may also contain channels for third party software. As a result, Windows Server allows you to collect all your events from separate servers and combine them in a central location. Alternatively, you could feed event logs to a Security Information and Event Management (SIEM) solution that isn’t Microsoft based.

While there is a lot of information collected by the events log by default, it is the auditing feature in Windows that determines what information gets collected and logged.

How to Check Windows Server Logs

There are two main graphical ways you can access the Windows Server event log:

  • Event Viewer Microsoft Management Console (MMC)
  • Windows Admin Center (WAC)

The WAC isn’t as fully-featured as the Event Viewer. Nonetheless, you can access the Event Viewer from the server or client machine(s) using Windows Administrative Tools. Alternatively, you can use the Windows Server Manager to run the Event Viewer.

Launching The Windows Server Manager

Again, there are quite a few ways you can check server event logs from Windows Server. One of the best ways is using Windows Server Manager which acts as a central hub for our server. By default, Windows Server Manager is a Windows Server start up application. This means that it’s one of the first applications to run when you launch Windows Server. However, you can also run the Server Manager from the start menu or search bar:

  • Open the Start Menu (WinKey).
  • Search through the applications list for Server Manager or type it into the search field.
  • Double click on the Server Manager item.

Server Manager logs

How to Launch The Event Viewer

Once again, the best way to check Windows Event Logs is through the Event Viewer. You can launch it from the Server Manager using the following steps:

  • Click on the top Tools menu button.
  • Search the list for Event Viewer.
  • Double click on it to open it .

Server Manager Event Viewer

Using The Roles and Server Groups Section To Check Events

You may have noticed that the Events Viewer isn’t the only place you can view events from the Server Manager. As seen, the Server Manager also allows you to view roles and server specific events on the dashboard. You can view File and Storage, Local Server, and All Servers events by using the various widgets in the dashboard.

Role and Server Group Events Windows Server Manager

Clicking on one of the Events options in these widgets will launch a screen similar to this one:

Server Manager Event Display

This is called the Events Detail View. It gives you a list of filtration options including:

  • Event Security Levels: Filter events according to their severity.
  • Event Sources: Origin of an event (applications, services, etc).
  • Servers: The machine the event occurred on.
  • Time Period: The hours and/or minutes the event occurred in between.
  • Event IDs: Each event has a unique ID. You can filter events using these IDs.

Again, we’ll stick to using the Event Viewer because it’s the most fully featured option.

Navigating Through the Event Viewer

Windows Event Log Main Screen

One of the most unfortunate facts about Windows Server’s event management system is its lack of built in alerts or notifications. However, you can apply a script or run a program that is triggered when a particular event enters one of your custom views.

Nevertheless, you should be able to see the four channels we previously mentioned under the Windows Logs folder. You can use the above image as a reference. Ultimately, this is where you will check your Windows Servers Log.

You will notice that the above image features an additional channel called Forwarded Events. This channel is used by servers that have been set up as event collectors. It allows you to see events from other servers.

If you scan through the Event Viewer tree, you should notice a top folder labeled Applications and Services Log.  It contains event channels related to installed server software and hardware.

Event Log Levels

When checking Windows Server Logs through the Event Viewer, you’re bound to run into a plethora of event types. They include:

  • Information: Logs information event. For instance, when a task is completed successfully or when the system informs the user of something.
  • Warning: Used to log system and software warnings. They don’t demand immediate action. However, they may warn you of a future problem, like disk space running out.
  • Error: Indicates a system, software, or hardware issue that requires immediate action. For instance, a driver failing to load upon start up.
  • Success Audit (Security log): This signifies the success of an audited security event. For instance, a user successfully logging onto the server or client.
  • Failure Audit (Security log): This signifies the success of an audited security event. For instance, a user failing to log onto a server or client.

It is time to explain How to Check Windows Server Logs (Windows Event Log Types). 

Event Log Types

In this section of the guide, you’ll explore the event types (Event Sources) you should be monitoring. Ultimately, keeping track of important logs requires you to use event sources to identify vulnerabilities in your system. Certainly, you’ll be able to find the event source by using the Source tab for each event.  

Event Source

Alternatively, you can create a custom view by:

  • Right clicking on any one of the folders or objects on the right tree panel eg. Windows Logs.
  • Next, select Create Custom View… from the context menu.

If you execute the above steps correctly, you should be presented with this screen. 

Custom Event View

You can then use either the filer screen or XML screen to create an event source-based view. 

1. Application Whitelisting

As shown, you should have a list of approved services and applications. Anything that doesn’t appear on your whitelist should be flagged as suspicious. Consequently, there are two systems built into the latest versions of Windows for application control:

  • AppLocker
  • Microsoft Defender Device Guard

You can either use these systems individually or in tandem. Regardless, DeviceGuard is considered the most difficult to configure but also the most secure. As such, admins may elect to use it over AppLocker. AppLocker is easy to bypass by compromising the Windows NT Kernel. Comparatively, the Device Guard is much more robust and much more secure against exploits against the Windows NT Kernel.

However, if it’s your first time working with application control software, it is recommended that you use AppLocker with the Event Viewer.

What Should You Do When You Encounter This Event?

Your event source is dependent on the application control solution you’ve chosen to use for black and whitelisting. For instance, any event related to the AppLocker will use AppLocker as a source. Likewise, if you use Microsoft Defender, Device Guard events will use DeviceGuard as a source.  It’s important that you investigate any suspicious events related to these sources. Correspondingly, bad actors may be trying to whitelist apps that you’ve previously blacklisted because of the vulnerabilities they impose on your system. You should:

  • Check your app control configurations.
  • Consult with a network security specialist to track down the person that may have changed your rules.
  • Change all necessary Passovers.

2. Randomly Cleared Events and Audit Logs

If you notice that some of your events have been randomly cleared, then your network/system has most likely been compromised by bad actors. Especially, these bad actors may be trying to hide malicious activity by purging events. At this  time it’s important to remember that event logs are not typically cleared during normal operations. As such, if you notice the following event logs, you should be worried:

Event Log Cleared

What Should You Do When You Encounter This Event?

Nevertheless, collecting logs centrally on a server that only you (or your network’s admin) can access is the best way to protect yourself against cleared event logs. This will allow you to view deleted or cleared event logs without restoring your server from a backup. You can then confirm if a bad actor compromised your system.

3.Account Usage

A variety of users will log in to your server(s). You can use these event types and IDs to detect unauthorized account usage and remote desktop logins. Some users can use Windows Remote Desktop to configure systems that they should not be allowed to. Equally, users should not be logging into your server using Remote Desktop when there are other tools such as Power Share, Windows Admin Console (WAC), etc.

You (or your network administrator) should especially be paying attention to privileged Active Directory groups such as the domain and enterprise admin groups. Furthermore, you must make sure that your system isn’t adding or removing users from these groups without permission.

Account lockouts are important events that should be monitored. They can often signify brute force attempts by malicious actors. These bad actors may be trying to guess a user’s password. Nevertheless, the following are the events that fall under this category:

How to Check Windows Server Logs Windows Event Log Types

What Should You Do When You Encounter This Event?

When you encounter this event, it’s important to connect all related users and/or groups. First step is to investigate why a specific user was locked out. Was it indeed a bad actor or have they forgotten their password? Once you’ve fully ascertained the reasons for the user’s failed login attempts, you can act accordingly. 

4. Group Policy Errors

Evidently, you use Group Policy Objects (GPOs) to configure and enforce your organization’s security policy. Thus, if the group policies you’ve set aren’t enforced, then your system may be compromised. In most cases, it may be the result of a bad actor attempting to prevent your system from enforcing certain policies so they can enact their own.

However, it can also be something benign or innocent. For instance, the group policy client may be failing for some reason. Regardless, it’s always important to monitor your group policies as they may indicate something nefarious occurring on your network..  

Microsoft Window Group Policy Events

What Should You Do When You Encounter This Event?

 Your group policies can be viewed in the GroupPolicy channel (Microsoft > Windows > GroupPolicy). It allows you to see if your system is applying Group Policy Objects (GPOs) successfully. Once you encounter any errors in this view, you should first determine why the error is concerning. It may not be the result of a breach or attempted exploit. One of your machines may be struggling with low system resources. Make sure to check if your GroupPolicies are operational. 

5. Software and Service Installation

By the same token, you may be regularly installing and updating software and services on your server. However, installations occur daily. Of course, this depends on the server’s usage and age. Freshly commissioned servers may require daily installations, backups, and updates. Nonetheless, if you see suspicious software and service-related events, then it may be a sign of malicious activity carried out by a bad actor.  

What Should You Do When You Encounter This Event?

Look out for keywords in events such as “Installed”, “New”, “Removed”, “Update”, and ”Updated”. You can find the above keywords by using a search or a custom view of your creation. You must investigate every suspicious occurrence you find and review logs to ensure that every software/service installation and removal has been approved.

6. Windows Updates

As with the desktop version of the operating system, Windows Server also requires regular updates. These updates are imperative because they often contain important system patches. If these Windows updates fail, it may leave your system vulnerable.

Consequently, you must check the WindowUpdateClient and Servicing event sources from the System channel. Alternatively, you can create a custom view filtered according to these event sources. Nevertheless, you must validate that there are no errors or information events that indicate Windows Update failures.

What Should You Do When You Encounter This Event?

The first thing you must do is investigate why your Windows Updates are being interrupted. It may not be a result of a malicious. Your server(s) may be low on system resources or your system may be experiencing a network error. As you investigate the source of the issue, you must ensure that your Windows Server operating system is up to date. You can manually download and install Windows Server Cumulative Updates. 

7. Windows Firewall

The Windows Firewall is enabled by default. It protects servers and clients against malicious activities from your internal trusted network. Henceforth, it’s just as important as any firewall you have segregated in your network. Thus, you must check that your firewall is it’s working, and if the status and/or rules have been updated or changed, etc.

Event sources to look out for include: Firewall, Firewall-Client, Firewall-CPL, Firewall-Driver, and Firewall-Service. Again, you can create a custom view with these event sources.

What Should You Do When You Encounter This Event?

Again, you must determine the source of the issue. Is someone trying to reconfigure your firewall? You should consider using third party firewalls for your internal system. There are other steps you can take to improve your overall cybersecurity.     

8. Application Crashes

Application crashes are fairly common. However, they may indicate a malicious attack where a bad actor is forcing processes and services to shut down. Therefore, you or your system administrator must check the event logs for instances of Blue Screen of Death (BSOD), Windows Error Reporting (WER), Application Crashes, and Hang events.

App Crash Events

What Should You Do When You Encounter This Event?

Again, you should determine the source of the crash, freeze, etc. Are the affected applications important to the security of your network? Which machines are they specifically related to?  This will help you decide if you must investigate further or change the posture of your network’s security.

Thank you for reading How to Check Windows Server Logs (Windows Event Log Types Explained). We shall conclude.

How to Check Windows Server Logs (Windows Event Log Types) Conclusion

Содержание

Просмотр системного журнала

Если в работе Windows 2012 появляется какая-то нестабильность, или появляются ошибки запускаустановки приложений, то это может быть связано с появлениями ошибок  в самой операционной системе.

Все системные ошибки и предупреждения можно найти в «Журнале системы«.

В нем сохраняется информация о событиях, записываемых системными компонентами Windows.

Для просмотра и сохранения системного журнала нужно выполнить шаги:

Открыть «Пуск«:

Открыть «Панель управления«:

В «Панели управления» выбрать «Просмотр журналов событий«

В открывшемся окне выбрать «Просмотр событий» -> «Журналы Windows» -> «Система«

Экспорт журнала

Системный журнал в полном объеме можно выгрузить путем нажатия на ссылку «Сохранить все события как…«

После нажатия ссылки  «Сохранить все события как…» нужно выбрать путь и имя файла для сохраняемого журнала.

При сохранении файла возможно появление окна «Отображение сведений«.

В данном окне нужно выбрать пункт «Отображать сведения для следуюших языков: Русский«

Готово


First published on TechNet on Sep 30, 2014


[This post comes to us courtesy of Swapnil Rane


from Commercial Technical Support]

This post will reduce your efforts to identify which log to refer to and where to find it. This can be very useful when you are troubleshooting issues on an Essentials server. We have compiled a list of important logs and their associated wizards below. There can be issues where we may have to refer to multiple logs.

Server-side Logs:

In Windows Server Essentials 2012 and 2012 R2, the location of the log files is under

%programdata%MicrosoftWindows ServerLogs

.

Service Integration Log Files:

O365/On-Premise Exchange/Intune

SharedServiceHost-EmailProviderServiceConfig.log

Windows Azure Backup

OnlineBackupGettingStartedWizard.log

Backup Log Files:

Server Backup Configuration wizard

SBCW.log

Server Backup restore wizard

ServerFFR.log

Client Backup Feature server side log

Backup-<date>.log

Client backup database cleanup

RunTask-BackupCleanup.log

Client backup database checker

RunTask-Consistency check

Storage and Devices Log Files:

User/Device management feature

SharedServiceHost-ManagementServiceConfig.log

Storage features

Storageservice.<date>.log

Storage related feature

Storageutil.<date>.log

Azure Backup Log Files:


Location: C:Program FilesWindows Azure Backup AgentTemp

Azure Backup Logs

CBEngineCurr.errlog

Failed Azure Backup Logs

LastBackupFailedFile#####.txt

Other Helpful Log Files:

DC Promo

DCPromo_date.log

Health evaluation schedule task

RunTask-AlertEvaluation.log

Macintosh Clients Status update

RunTask-MacintoshStatusReport.log

Server DNS status

ServerBeacon.log

Customer Experience Improvement

RunTask-SaveCustomerExperienceImprovementProgramData.log

Program and Service Quality Measurement Log Files:

CA Role installation

CA_ROLE_INSTALL.log

Media pack installation (2012 R2)

MediaPackInstalltionWizard.xxxx.log

Media Service (Specially with RWA)

MediaStreamingProvider.log

O365 (Assign/Un-assign Accounts)

TaskStatus-OIMAddin.log

Client-side Logs:

The client-side log files are located in the folder

%programdata%MicrosoftWindows Serverlogs

. They are as:

Client Deployment

ClientDeploy.log

Client package installation Failures

ComputerConnector.log

Client backup restore mount driver

BackupDriverInstaller.log

Client operation for File history Sync

ClientOperator.log

Main log for client launch pad

LaunchPad.log

Password synchronization feature in AAD

PasswordSyncClientAlerts.log

Add-in feature on client

RunTask-Add-in Management.log

Health evaluation schedule task

RunTask-AlertEvaluation.log

Client Backup scheduled task

RunTask-ClientComputeBackkup.log

Connector uninstall cleanup task

RunTask-Connector cleanup.log

Update health definition file from server to client task

RunTask-HealthDefinitionUpdate.log

RDP feature for RWA

RunTask-RDP Group Configuration.log

Client VPN connectivity issues

RunTask-VPN Routes Repair.log

Client network status update

ServerLocator-<date>.log

Client deployment API call (Client deployment fails)

Setupapi.dev.log

Health alert feature

SharedServiceHost-HealthServiceConfig.log

The above logs should be able to guide you through the process of troubleshooting effectively on Essentials relevant issues.

Here is a list of where you can find important log files for Windows Server 2012 Essentials and Windows Server 2012 R2 Essentials.

Server-side Logs:

In Windows Server Essentials 2012 and 2012 R2, the location of the log files is under %programdata%MicrosoftWindows ServerLogs.

Service Integration Log Files:

O365/On-Premise Exchange/Intune   SharedServiceHost-EmailProviderServiceConfig.log
Windows Azure Backup   OnlineBackupGettingStartedWizard.log

Backup Log Files:

Server Backup Configuration wizard SBCW.log
Server Backup restore wizard ServerFFR.log
Client Backup Feature server side log Backup-<date>.log
Client backup database cleanup RunTask-BackupCleanup.log
Client backup database checker RunTask-Consistency check

Storage and Devices Log Files:

User/Device management feature SharedServiceHost-ManagementServiceConfig.log
Storage features Storageservice.<date>.log
Storage related feature Storageutil.<date>.log

Azure Backup Log Files:

Location: C:Program FilesWindows Azure Backup AgentTemp
Azure Backup Logs CBEngineCurr.errlog
Failed Azure Backup Logs LastBackupFailedFile#####.txt

Other Helpful Log Files:

DC Promo DCPromo_date.log
Health evaluation schedule task RunTask-AlertEvaluation.log
Macintosh Clients Status update RunTask-MacintoshStatusReport.log
Server DNS status ServerBeacon.log
Customer Experience Improvement RunTask-SaveCustomerExperienceImprovementProgramData.log

Program and Service Quality Measurement Log Files:

CA Role installation CA_ROLE_INSTALL.log
Media pack installation (2012 R2) MediaPackInstalltionWizard.xxxx.log
Media Service (Specially with RWA) MediaStreamingProvider.log
O365 (Assign/Un-assign Accounts) TaskStatus-OIMAddin.log

Client-side Logs:

The client-side log files are located in the folder %programdata%MicrosoftWindows Serverlogs. They are as:

Client Deployment ClientDeploy.log
Client package installation Failures ComputerConnector.log
Client backup restore mount driver BackupDriverInstaller.log
Client operation for File history Sync ClientOperator.log
Main log for client launch pad LaunchPad.log
Password synchronization feature in AAD PasswordSyncClientAlerts.log
Add-in feature on client RunTask-Add-in Management.log
Health evaluation schedule task RunTask-AlertEvaluation.log
Client Backup scheduled task RunTask-ClientComputeBackkup.log
Connector uninstall cleanup task RunTask-Connector cleanup.log
Update health definition file from server to client task RunTask-HealthDefinitionUpdate.log
RDP feature for RWA RunTask-RDP Group Configuration.log
Client VPN connectivity issues RunTask-VPN Routes Repair.log
Client network status update ServerLocator-<date>.log
Client deployment API call (Client deployment fails) Setupapi.dev.log
Health alert feature SharedServiceHost-HealthServiceConfig.log

Reference – http://blogs.technet.com/b/sbs/archive/2014/09/30/windows-server-essentials-log-files.aspx 

Resources for Small Business

В этой статье мы рассмотрим, как получить и проанализировать логи RDP подключений в Windows. Логи RDP подключений позволяют администраторам терминальных RDS серверов/ферм получить информацию о том, какие пользователи подключались к серверу, когда был выполнен вход и когда сеанс завершен, с какого устройства (имя или IP адрес) подключался пользователь.

Описанные методики получения и исследования RDP логов применима как к Windows Server 2022/2019/2016/2012R2, так и для десктопных версий Windows 11, 10, 8.1 c.

Содержание:

  • События RDP подключений в журналах Windows (Event Viewer)
  • Получаем логи RDP подключений в Windows с помощью PowerShell
  • Логи RDP подключений на клиентах Windows

События RDP подключений в журналах Windows (Event Viewer)

Когда пользователь удаленно подключается к RDS серверу или удаленному столу Windows (RDP), информация об этих событиях сохраняется в журналы Windows. Рассмотрим основные этапы RDP подключения и связанные с ними события в Event Viewer.

  1. Network Connection
  2. Authentication
  3. Logon
  4. Session Disconnect/Reconnect
  5. Logoff

Network Connection: – событие установления сетевого подключение к серверу от RDP клиента пользователя. Событие с EventID – 1149 (Remote Desktop Services: User authentication succeeded). Наличие этого события не свидетельствует об успешной аутентификации пользователя. Этот журнал находится в разделе Applications and Services Logs -> Microsoft -> Windows -> Terminal-Services-RemoteConnectionManager -> Operational. Включите фильтр по данному событию (ПКМ по журналу-> Filter Current Log -> EventId 1149).

1149 Terminal-Services-RemoteConnectionManager

С помощью PowerShell можно вывести список всех попыток RDP подключений:

$RDPAuths = Get-WinEvent -LogName 'Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational' -FilterXPath '<QueryList><Query Id="0"><Select>*[System[EventID=1149]]</Select></Query></QueryList>'
[xml[]]$xml=$RDPAuths|Foreach{$_.ToXml()}
$EventData = Foreach ($event in $xml.Event)
{ New-Object PSObject -Property @{
TimeCreated = (Get-Date ($event.System.TimeCreated.SystemTime) -Format 'yyyy-MM-dd hh:mm:ss K')
User = $event.UserData.EventXML.Param1
Domain = $event.UserData.EventXML.Param2
Client = $event.UserData.EventXML.Param3
}
} $EventData | FT

вывести журнал подключений к RDP/RDS серверу с помощью powershell

В результате у вас получится список с историей всех сетевых RDP подключений к данному серверу. В событии содержится имя пользователя, домен (если используется NLA аутентификация, при отключенном NLA текст события выглядит иначе) и IP адрес компьютера пользователя.

Remote Desktop Services: User authentication succeeded

Authentication: – успешная или неудачная аутентификация пользователя на сервере. Журнал Windows -> Security. Здесь нас могут интересовать события с EventID – 4624 (успешная аутентификация — An account was successfully logged on) или 4625 (ошибка аутентификации — An account failed to log on). Обратите внимание на значение LogonType в событии.

  • LogonType = 10 или 3 — при входе через терминальную службу RDP —.
  • LogonType = 7, значит выполнено переподключение к уже существующему RDP сеансу.
  • LogonType = 5 – событие RDP подключения к консоли сервера (в режиме mstsc.exe /admin)

Вы можете использовать события с ошибками аутентификации для защиты от удаленного перебора паролей через RDP. СВы можете автоматически блокировать на файерволе IP адреса, с которых выполняется подбор пароля, простым PowerShell скриптом (см. статью).

rdp событие аутентфикации An account was successfully logged on

При этом имя пользователя содержится в описании события в поле Account Name, имя компьютера в Workstation Name, а имя пользователя в Source Network Address.

Обратите внимание на значение поля LogonID – это уникальный идентификатор сессии пользователя, с помощью которого можно отслеживать дальнейшую активность данного пользователя. Но при отключении от RDP сессии (disconnect) и повторного переподключения к той же сессии, пользователю будет выдан новый TargetLogonID (хотя RDP сессия осталась той же самой).

Вы можете получить список событий успешных авторизаций по RDP (событие 4624) с помощью такой команды PowerShell.

Get-EventLog security -after (Get-date -hour 0 -minute 0 -second 0) | ?{$_.eventid -eq 4624 -and $_.Message -match 'logon type:s+(10)s'} | Out-GridView

получиь журнал RDP входов с помощью PowerShell

Logon: – RDP вход в систему, EventID – 21 (Remote Desktop Services: Session logon succeeded. Это событие появляется после успешной аутентификации пользователя. Этот журнал находится в разделе Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Как вы видите, здесь можно узнать идентификатор RDP сессии для пользователя — Session ID.

Remote Desktop Services: Session logon succeeded

Событие с EventID – 21 (Remote Desktop Services: Shell start notification received) означает успешный запуск оболочки Explorer (появление окна рабочего стола в RDP сессии).

Session Disconnect/Reconnect – события отключения и переподключения к сессии имеют разные коды в зависимости от того, что вызвало отключение пользователя (отключение по неактивности, заданному в таймаутах для RDP сессий; выбор пункта Disconnect в сессии; завершение RDP сессии другим пользователем или администратором и т.д.). Эти события находятся в разделе журналов Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Рассмотрим RDP события, которые могут быть полезными:

  • EventID – 24 (Remote Desktop Services: Session has been disconnected) – пользователь отключился от RDP сессии.
  • EventID – 25 (Remote Desktop Services: Session reconnection succeeded) – пользователь переподключился к своей имеющейся RDP сессии на сервере.
  • EventID – 39 (Session <A> has been disconnected by session <B>) – пользователь сам отключился от своей RDP сессии, выбрав соответствующий пункт меню (а не просто закрыл окно RDP клиента). Если идентификаторы сессий разные, значит пользователя отключил другой пользователь (или администратор).
  • EventID – 40 (Session <A> has been disconnected, reason code <B>). Здесь нужно смотреть на код причины отключения в событии. Например:
    • reason code 0 (No additional information is available) – обычно говорит о том, что пользователь просто закрыл окно RDP клиента.
    • reason code 5 (The client’s connection was replaced by another connection) – пользователь переподключился к своей старой сессии.
    • reason code 11 (User activity has initiated the disconnect) – пользователь сам нажал на кнопку Disconnect в меню.

Событие с EventID – 4778 в журнале Windows -> Security (A session was reconnected to a Window Station). Пользователь переподключился к RDP сессии (пользователю выдается новый LogonID).

Событие с EventID 4779 в журнале Windows -> Security (A session was disconnected from a Window Station). Отключение от RDP сеанса.

Logoff: – выход пользователя из системы. При этом в журнале Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational регистрируется событие с EventID 23 (Remote Desktop Services: Session logoff succeeded).

Remote Desktop Services: Session logoff succeeded

При этом в журнале Security нужно смотреть событие EventID 4634 (An account was logged off).

Событие Event 9009 (The Desktop Window Manager has exited with code (<X>) в журнале System говорит о том, что пользователь инициировал завершение RDP сессии, и окно и графический shell пользователя был завершен.

EventID 4647 — User-initiated logoff

Получаем логи RDP подключений в Windows с помощью PowerShell

Ниже представлен небольшой PowerShell скрипт, который выгружает из журналов терминального RDS сервера историю всех RDP подключений за текущий день. В полученной таблице указано время подключения, IP адрес клиента и имя пользователя (при необходимости вы можете включить в отчет другие типы входов).

Get-EventLog -LogName Security -after (Get-date -hour 0 -minute 0 -second 0)| ?{(4624,4778) -contains $_.EventID -and $_.Message -match 'logon type:s+(10)s'}| %{
(new-object -Type PSObject -Property @{
TimeGenerated = $_.TimeGenerated
ClientIP = $_.Message -replace '(?smi).*Source Network Address:s+([^s]+)s+.*','$1'
UserName = $_.Message -replace '(?smi).*ssAccount Name:s+([^s]+)s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*ssAccount Domain:s+([^s]+)s+.*','$1'
LogonType = $_.Message -replace '(?smi).*Logon Type:s+([^s]+)s+.*','$1'
})
} | sort TimeGenerated -Descending | Select TimeGenerated, ClientIP `
, @{N='Username';E={'{0}{1}' -f $_.UserDomain,$_.UserName}} `
, @{N='LogType';E={
switch ($_.LogonType) {
2 {'Interactive - local logon'}
3 {'Network conection to shared folder)'}
4 {'Batch'}
5 {'Service'}
7 {'Unlock (after screensaver)'}
8 {'NetworkCleartext'}
9 {'NewCredentials (local impersonation process under existing connection)'}
10 {'RDP'}
11 {'CachedInteractive'}
default {"LogType Not Recognised: $($_.LogonType)"}
}
}}

логи RDP подключений к RDS серверу с IP адресами и учетными записями

Можно экспортировать логи RDP подключений из журнала в CSV файл (для дальнейшего анализа в таблице Excel). Экспорт журнала можно выполнить из консоли Event Viewer (при условии что логи не очищены) или через командную строку:

WEVTUtil query-events Security > c:pssecurity_log.txt

Или с помощью PowerShell:

get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:psrdp-log.csv  -Encoding UTF8

Если ваши пользователи подключаются к RDS серверам через шлюз удаленных рабочих столов Remote Desktop Gateway, вы можете обрабатывать логи подключений пользователей по журналу Microsoft-Windows-TerminalServices-Gateway по EventID 302. Например, следующий PowerShell скрипт выведет полную историю подключений через RD Gateway указанного пользователя:

$rdpusername="kbuldogov"
$properties = @(
@{n='User';e={$_.Properties[0].Value}},
@{n='Source IP Adress';e={$_.Properties[1].Value}},
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='Target RDP host';e={$_.Properties[3].Value}}
)
(Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-Gateway/Operational';ID='302'} | Select-Object $properties) -match $rdpusername

powershell поиск в логах удаленных RDP подключений на remote desktop gateway в windows server 2019

Другие события, связанные с подключениями пользователей на RD Gateway в журнале Microsoft-Windows-TerminalServices-Gateway:

  • 300
    The user %1, on client computer %2, met resource authorization policy requirements and was therefore authorized to connect to resource %4
  • 302
    The user %1, on client computer %2, connected to resource %4
  • 303
    The user %1, on client computer %2, disconnected from the following network resource: %4. Before the user disconnected, the client transferred %6 bytes and received %5 bytes. The client session duration was %7 seconds.

Список текущих RDP сессий на сервере можно вывести командой:

qwinsta

Команда возвращает как идентификатор сессии (ID), имя пользователя (USERNAME)и состояние (Active/Disconnect). Эту команду удобна использовать, когда нужно определить ID RDP сессии пользователя при теневом подключении.

Qwinsta

Список запущенных процессов в конкретной RDP сессии (указывается ID сессии):

qprocess /id:157

qprocess

Логи RDP подключений на клиентах Windows

Также вы можете изучать логи исходящих подключений на стороне RDP клиента. Они доступны в журнале событий Application and Services Logs -> Microsoft -> Windows -> TerminalServices-ClientActiveXCore -> Microsoft-Windows-TerminalServices-RDPClient -> Operation.

Например, событие с Event ID 1102 появляется, когда компьютер устанавливает подключение с удаленным RDS хостом Windows Server или компьютером с Windows 10/11 с включенной службой RDP (десктопные версии Windows также поддерживают несколько одновременных rdp подключений).

The client has initiated a multi-transport connection to the server 192.168.31.102.

событие с ID 1102 в журнале Microsoft-Windows-TerminalServices-RDPClient событие подключения к RDP серверу на клиенте

Следующий RDP скрипт выведет историю RDP подключений на указанном компьютере (для получения событий Event Log используется командлет Get-WinEvent):

$properties = @(
@{n='TimeStamp';e={$_.TimeCreated}}
@{n='LocalUser';e={$_.UserID}}
@{n='Target RDP host';e={$_.Properties[1].Value}}
)
Get-WinEvent -FilterHashTable @{LogName='Microsoft-Windows-TerminalServices-RDPClient/Operational';ID='1102'} | Select-Object $properties

powershell вывести история RDP подключений на клиентском компьютере

Скрипт возвращает SID пользователей, которые инициировали RDP подключения на этом компьютере и DNS имена/IP адреса серверов, к которым подключались пользователи. Вы можете преобразовать SID в имена пользователей.

Также история RDP подключений пользователя хранится в реестре.

Обновлено 23.03.2022

Как посмотреть логи windows

Всем привет, тема стать как посмотреть логи windows. Что такое логи думаю знают все, но если вдруг вы новичок, то логи это системные события происходящие в операционной системе как Windows так и Linux, которые помогают отследить, что, где и когда происходило и кто это сделал. Любой системный администратор обязан уметь читать логи windows.

Примером из жизни может служить ситуация когда на одном из серверов IBM, выходил из строя диск и для технической поддержки я собирал логи сервера, для того чтобы они могли диагностировать проблему. За собирание и фиксирование логов в Windows отвечает служба Просмотр событий. Просмотр событий это удобная оснастка для получения логов системы.

Как открыть в просмотр событий

Зайти в оснастку Просмотр событий можно очень просто, подойдет для любой версии Windows. Нажимаете волшебные кнопки

Win+R и вводите eventvwr.msc

Откроется у вас окно просмотр событий windows в котором вам нужно развернуть пункт Журналы Windows. Пробежимся по каждому из журналов.

Журнал Приложение, содержит записи связанные с программами на вашем компьютере. В журнал пишется когда программа была запущена, если запускалась с ошибкоу, то тут это тоже будет отражено.

логи windows-01

Журнал аудит, нужен для понимания кто и когда что сделал. Например вошел в систему или вышел, попытался получить доступ. Все аудиты успеха или отказа пишутся сюда.

логи windows-02

Пункт Установка, в него записывает Windows логи о том что и когда устанавливалось Например программы или обновления.

логи windows-03

Самый важный журнал Это система. Сюда записывается все самое нужное и важное. Например у вас был синий экран bsod, и данные сообщения что тут заносятся помогут вам определить его причину.

логи windows-04

Так же есть логи windows для более специфических служб, например DHCP или DNS. Просмотр событий сечет все :).

логи windows-05

Фильтрация в просмотре событий

Предположим у вас в журнале Безопасность более миллиона событий, наверняка вы сразу зададите вопрос есть ли фильтрация, так как просматривать все из них это мазохизм. В просмотре событий это предусмотрели, логи windows можно удобно отсеять оставив только нужное. Справа в области Действия есть кнопка Фильтр текущего журнала.

Фильтрация в просмотре событий

Вас попросят указать уровень событий:

  • Критическое
  • Ошибка
  • Предупреждение
  • Сведения
  • Подробности

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

Фильтрация в просмотре событий-2

Так что как видите разобрать логи windows очень просто, ищем, находим, решаем. Так же может быть полезным быстрая очистка логов windows:

  • Как очистить просмотр событий с помощью PowerShell
  • Как почистить все журналы windows с помощью скрипта

Посмотреть логи windows PowerShell

Было бы странно если бы PowerShell не умел этого делать, для отображения log файлов открываем PowerShell и вводим вот такую команду

Get-EventLog -Logname ‘System’

В итоге вы получите список логов журнала Система

список логов журнала Система

Тоже самое можно делать и для других журналов например Приложения

Get-EventLog -Logname ‘Application’

список логов журнала Приложения

небольшой список абревиатур

  • Код события — EventID
  • Компьютер — MachineName
  • Порядковый номер события — Data, Index
  • Категория задач — Category
  • Код категории — CategoryNumber
  • Уровень — EntryType
  • Сообщение события — Message
  • Источник — Source
  • Дата генерации события — ReplacementString, InstanceID, TimeGenerated
  • Дата записи события — TimeWritten
  • Пользователь — UserName
  • Сайт — Site
  • Подразделение — Conteiner

Например, для того чтобы в командной оболочке вывести события только со столбцами «Уровень», «Дата записи события», «Источник», «Код события», «Категория» и «Сообщение события» для журнала «Система», выполним команду:

Get-EventLog –LogName ‘System’ | Format-Table EntryType, TimeWritten, Source, EventID, Category, Message

вывести события

Если нужно вывести более подробно, то заменим Format-Table на Format-List

Get-EventLog –LogName ‘System’ | Format-List EntryType, TimeWritten, Source, EventID, Category, Message

Как видите формат уже более читабельный.

Format-List

Так же можно пофильтровать журналы например показать последние 20 сообщений

Get-EventLog –Logname ‘System’ –Newest 20

показать последние 20 сообщений

Или выдать список сообщение позднее  1 ноября 2014

Get-EventLog –LogName ‘System’ –After ‘1 ноября 2014’

Дополнительные продукты

Так же вы можете автоматизировать сбор событий, через такие инструменты как:

  • Комплекс мониторинга Zabbix
  • Через пересылку событий средствами Windows на сервер коллектор
  • Через комплекс аудита Netwrix
  • Если у вас есть SCOM, то он может агрегировать любые логи Windows платформ
  • Любые DLP системы

Так что вам выбирать будь то просмотр событий или PowerShell для просмотра событий windows, это уже ваше дело. Материал сайта pyatilistnik.org

Удаленный просмотр логов

  • Первый метод

Не так давно в появившейся операционной системе Windows Server 2019, появился компонент удаленного администрирования Windows Admin Center. Он позволяет проводить дистанционное управление компьютером или сервером, подробнее он нем я уже рассказывал. Тут я хочу показать, что поставив его себе на рабочую станцию вы можете подключаться из браузера к другим компьютерам и легко просматривать их журналы событий, тем самым изучая логи Windows. В моем примере будет сервер SVT2019S01, находим его в списке доступных и подключаемся (Напомню мы так производили удаленную настройку сети в Windows).

Удаленное подключение через Windows Admin Center

Далее вы выбираете вкладку «События», выбираете нужный журнал, в моем примере я хочу посмотреть все логи по системе. С моей точки зрения тут все просматривать куда удобнее, чем из просмотра событий. Плюсом будет, то что вы это можете сделать из любого телефона или планшета. В правом углу есть удобная форма поиска

Просмотр логов Windows через Windows Admin Center

Если нужно произвести более тонкую фильтрацию логов, то вы можете воспользоваться кнопкой фильтра.

Фильтрация логов в Windows Admin Center

Тут вы так же можете выбрать уровень события, например оставив только критические и ошибки, задать временной диапазон, код событий и источник.

Настройка фильтрации логов Windows через Windows Admin Center

Вот пример фильтрации по событию 19.

Удаленный просмотр логов Windows

Очень удобно экспортировать полностью журнал в формат evxt, который потом легко открыть через журнал событий. Так, что Windows Admin Center, это мощное средство по просмотру логов.

  • Второй метод

Второй способ удаленного просмотров логов Windows, это использование оснастки управление компьютером или все той же «Просмотр событий». Чтобы посмотреть логи Windows на другом компьютере или сервере, в оснастке щелкните по верхнему пункту правым кликом и выберите из контекстного меню «Подключиться к другому компьютеру«.

Подключиться к другому компьютеру

Указываем имя другого компьютера, в моем примере это будет SVT2019S01

Указание имени удаленного компьютера для просмотра логов

Если все хорошо и нет блокировок со стороны брандмауэра или антивируса, то вы попадете в удаленный просмотр событий .если будут блокировки, то получите сообщение по типу, что не пролетает трафик COM+.

Ошибка удаленного просмотра логов Windows

Так же хочу отметить, что есть целые системы агрегации логов, такие как Zabbix или SCOM, но это уже другой уровень задач. На этом у меня все, с вами был Иван Семин, автор и создатель IT портала Pyatilistnik.org.

Средство просмотра событий Windows обрабатывается основной службой журнала событий. Средство просмотра событий регистрирует историю запуска и завершения работы сервера. Так же она отслеживает действия каждого пользователя во время работы устройства. Записывает ошибки, и другие сообщения и предупреждения которые возникают на Windows Server. 

В этой статье мы узнаем, как проверить журналы выключения/перезагрузки на VPS серверах Windows 2012, 2016 и 2019. 

Рассмотрим некоторые наиболее распространенные коды связанные со временем запуска и завершения работы сервера.

41:  показывает, что ваш сервер перезагрузился, но не выключился полностью.
6005: показывает, что служба журнала событий была запущена.
1074:  это событие показывает, когда приложение принудительно выключает или перезагружает ваш VPS сервер. Благодаря этому можно  узнать, когда вы, или кто-то другой перезапустил или выключил сервер из меню «Пуск» или через CTRL+ALT+DEL.
6008: это событие появляется если ваш компьютер был выключен, или ушел в перезагрузку, через синий экран смерти.
6006: это событие показывает когда сервер корректно завершил свою работу.

Как просмотреть данные события?

Нажмите Win + R и введите eventvwr


В левой части панели откройте «Журналы Windows => Система»


В колонке Event ID мы увидим список событий, произошедших во время работы Windows. Журнал событий можно сортировать по идентификатору события.

Для того что бы отсортировать нужные намо события, с правой стороны, выберем «Фильтр текущего журнала»

Теперь введите нужные нам события, через запятую, 41, 1074, 6006, 6008, 6006 и нажмите Ок.


Теперь мы можем наблюдать журнал событий с завершением работы нашего сервера VPS.

Так же мы можем просмотреть журнал событий безотказной работы сервера. Этому соответствует идентификатор 6013. 

 Просмотр журнала выключения и перезапуска сервера с помощью PowerShell

Если нам нужно быстро просмотреть журналы выключения/перезагрузки сервера, можно воспользоваться коммандой Get-EventLog в оболочке PowerShell. 

Что бы отфильтровать последнюю 1000 записей в журнале, и отобразить только те события которые нам нужны, (41, 1074, 6006, 6008, 6006) выполним эту команду в PowerShell:

Get-EventLog System -Newest 1000 | ` Where EventId -in 41,1074,6006,6008 | ` Format-Table TimeGenerated,EventId,UserName,Message -AutoSize -wrap

Теперь вы можете самостоятельно проверить по какой причине был перезагружен/выключен ваш севрер.

Table of Contents

  • Find event and error logs for Server Manager
  • Server Manager startup errors
  • Server Manager operations errors
  • Additional references

This article is Part III of the Server Manager Troubleshooting Guide. Other parts:

  • Windows Server 2012 — Server Manager Troubleshooting Guide, Part I: Overview
  • Windows Server 2012 — Server Manager Troubleshooting
    Guide, Part II: Troubleshoot Manageability Status Errors in Server Manager

This article describes how to find event and error log files that are related to Server Manager in Windows Server® 2012, and shows common event and error messages that can occur in Server Manager operations.

Find event and error logs for Server Manager

The following table shows Event Tracing for Windows channel paths to Server Manager event and error logs. The default log size for Server Manager logs is 1 MB. If you are managing a large number of servers with Server Manager (for example, more than 10 or
15 servers), you might want to increase the log size. For more information about how to increase the size of an event log, see
Set Maximum Log Size on Microsoft TechNet.

Component Event Tracing for Windows Channels Comment

Server Manager console

Applications And Services LogsMicrosoftWindowsServerManager-MultiMachine

Client operations events; stored on the computer that is running Server Manager

Server Manager Management Provider

…ServerManager-ManagementProvider

Events in this log are stored on the managed server

Add Roles and Features Wizard

…ServerManager-MultiMachine

Add Roles and Features Wizard Workflow

…ServerManager-MultiMachine

Event IDs 4000-4099

Server Manager Deployment Provider

…ServerManager-DeploymentProvider

Windows PowerShell Workflow general

…PowerShell

Event 45079 shows each activity run

Configure Remote Management task

…ServerManager-ConfigureSMRemoting


Server Manager startup errors

The following table describes errors that can occur when Server Manager is starting.

Issue Type Underlying Source Message from WinRM or Providers (shown in Task Details pane) Possible Causes and Suggested Resolutions

Server Manager startup error

Server Manager cannot load the server list. Click OK to reset the server list and continue. Click
Cancel to close Server Manager, and try to repair the server list manually in the XML server list file at the following location: %windir%Users<user name>AppDataRoamingMicrosoftWindowsServerManagerServerList.xml

Data in the serverlist.xml file is not valid.

Server Manager startup error

Error Starting Services: Server Manager could not start the task due to the following error: The Windows Remote Management (WS-Management) service is not running, and attempts to start the service have failed.

WinRM 3.0 is either turned off or cannot run properly on the client computer. Make sure the WinRM 3.0 service is running.


Server Manager operations errors

Displayed Error Message (in Task Details) Error Condition and Possible Causes

When you run the Add Roles and Features Wizard to add roles to a server in the Server Manager pool that is running a newer release of Windows Server, the following message dialog box is displayed: «Server Manager is collecting inventory data. The wizard
will be available after data collection finishes.»

Server Manager cannot be used to manage servers that are running a newer release of Windows Server than the release on which you are running Server Manager. Server Manager running on Windows 8 as part of Remote Server Administration Tools cannot be used
to manage a server that is running Windows Server 2012 R2, for example.

The system cannot get event data because the Windows Event Log service is stopped or not accessible.

Events data cannot be retrieved because the event log service on the target server is stopped.

When you run the Add Roles and Features Wizard to add roles to a server in the Server Manager pool that is running a newer release of Windows Server, the following message dialog box is displayed: «Server Manager is collecting inventory data. The wizard
will be available after data collection finishes.»

Server Manager cannot be used to manage servers that are running a newer release of Windows Server than the release on which you are running Server Manager. Server Manager running on Windows 8 as part of Remote Server Administration Tools cannot be used
to manage a server that is running Windows Server 2012 R2, for example.

The system cannot get service status because of insufficient access rights.

Services data can’t be retrieved because the Server Manager user does not have required access rights. Server Manager cannot communicate with Service Control Manager on the target server. This can occur when a user is not an administrator on the target server,
but is a standard user.

Best Practices Analyzer is not installed.

Errors occurred while running BPA scan on <role name>.

The following errors can be displayed when users run BPA scans in a Windows PowerShell console.

  • The specified module ‘BestPractices’ was not loaded because no valid module file was found in any module directory.
  • The term ‘<BPA cmdlet name>’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  • Errors occurred while running BPA scan on <role name>.

Best Practices Analyzer is not installed on target servers that are running Windows Server 2012 or Windows Server 2008 R2. This most likely means that Windows PowerShell is not installed. Run the following cmdlet on the computer that is running Server Manager
to install Windows PowerShell on the target server: Install-WindowsFeature -Name PowerShell –ComputerName <target server name>. On Windows Server 2008 R2, install the
Windows Management Framework 3.0 download package to get Windows PowerShell 3.0. Install prerequisites for Windows Management Framework 3.0 by following instructions in
Managing Downlevel Windows-based Servers from Server Manager in Windows Server 2012 to resolve this error. BPA cannot be installed or run on servers that are running releases of Windows
Server that are older than Windows Server 2008 R2.

You cannot get performance data for computers that run Windows Server 2008 and Windows Server 2008 R2 until KB 2682011 is installed on those operating systems. Install KB 2682011 or a superseding update on this computer, and then try this operation again.

This error occurs on older Windows Server operating systems (Windows Server 2008 R2 and Windows Server 2008) when performance counters have been turned on, but the update associated with
KB 2682011 has not yet been installed on the older operating systems. Until the update is applied, performance counters are running, but the Server Manager provider cannot get the
data.

The system cannot get role and feature data because of the following error: <error code>, extended error: <error code>, message: <specific error message from source>.

Server Manager cannot get role and feature data for older operating systems (Windows Server 2008 R2 and Windows Server 2008). Verify that
Windows Management Framework 3.0 has been installed on the target server. This error is rare. Search for the specific, underlying error code on
Microsoft TechNet to get more information.

The system cannot get role and feature data because of the following error: <error code>, extended error: <error code>, message: <specific error message from source>

Server Manager cannot get role and feature data from a server that is running Windows Server 2012. This error is rare. Search for the specific, underlying error code on
Microsoft TechNet to get more information.

The <task name> task could not be enabled. Error: <error code>

A standard user cannot enable the Server Manager Performance Monitor data collection task. This task starts Server Manager performance counters whenever the computer that is running Server Manager is restarted.

The <task name> collector could not be enabled. Error: <error code>

A standard user does not have adequate access rights to enable the Server Manager Performance Monitor data collection task. Typically, the preceding error message is displayed first.

The <task name> task could not be disabled. Error: <error code>

A standard user cannot disable the Server Manager Performance Monitor data collection task. This task stops Server Manager performance counters.

The <task name> collector could not be disabled. Error: <error code>

A standard user does not have adequate access rights to disable the Server Manager Performance Monitor data collection task. Typically, the preceding error message is displayed first.

The system cannot access one or more event logs because of insufficient access rights, data that is not valid, or other reasons. For more information, see the Operational channel in the ServerManager-ManagementProvider error log on the target server.

The Server Manager provider cannot access event logs because the user does not have adequate access rights. This is a common error for standard (non-administrative) users of Server Manager, because by default, they do not have access rights to get event
data from managed servers. To allow standard users to access event logs on a server, run the Enable-ServerManagerStandardUserRemoting cmdlet on the target server. For more information about how to use this cmdlet, see
Enable-ServerManagerStandardUserRemoting in the Windows PowerShell cmdlet Help topics.

Events from <query file name> could not be enumerated.

The Server Manager provider cannot read a saved query because the query file is not readable.

The system cannot access information for one or more services because of insufficient access rights or other reasons. For more information, see the Operational channel in the ServerManager-ManagementProvider log on the target server.

This error is typically displayed when standard users have attempted to get information that, by default, they do not have access to collect and view in Server Manager. If the standard user should be able to access the information, run the Enable-ServerManagerStandardUserRemoting
cmdlet on the target server. For more information about how to use this cmdlet, see
Enable-ServerManagerStandardUserRemoting in the Windows PowerShell cmdlet Help topics.

No results were found for one or more BPA models. Run a BPA scan on all roles that are installed on this server, and then try this operation again.

To clear this error, a Best Practices Analyzer (BPA) scan must be run on roles after they are installed on your managed servers. For more information about running BPA scans, see
Run Best Practices Analyzer Scans and Manage Scan Results.

The system was unable to open one or more BPA results because the results either do not exist, the results are not readable, or you do not have sufficient access rights to open them. For more information, see the Operational channel in the ServerManager-ManagementProvider
error log on the target server.

This error typically means that a BPA scan must be run on one or more roles on the target server. Although this error message is similar to the preceding error, it can also occur if BPA result files cannot be read or are otherwise inaccessible (due to insufficient
user access rights, for example). This error can be displayed to standard users, because only administrators can access BPA results.

You cannot resolve this error by running the Enable-ServerManagerStandardUserRemoting cmdlet; the cmdlet does not let standard users access BPA results or run BPA scans. Only administrators can run BPA scans and get BPA results.


Additional references

  • KB 2682011
  • Windows Management Framework 3.0
  • Enable-ServerManagerStandardUserRemoting
  • Run Best Practices Analyzer Scans and Manage Scan Results
  • Install or Uninstall Roles, Role Services, or Features
  • Configure Features on Demand in Windows Server
  • Install .NET Framework 3.5 and Other Features on Demand
  • Server Manager Troubleshooting Guide, Part I: Overview
  • Server Manager Troubleshooting Guide, Part II: Troubleshoot
    Manageability Status Errors in Server Manager

  • Как посмотреть количество процессоров на windows 10
  • Как посмотреть логи в windows 10 через cmd
  • Как посмотреть кэш на компьютере windows 10
  • Как посмотреть количество оперативной памяти на windows 11
  • Как посмотреть кто занял порт windows