Applications and services logs microsoft windows terminalservices localsessionmanager operational

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

В этой статье мы рассмотрим, как получить и проанализировать логи 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 подключений пользователя хранится в реестре.

In this article, we’ll describe how to get and audit the RDP connection logs in Windows. The RDP connection logs allow RDS terminal servers administrators to get information about which users logged on to the server when a specific RDP user logged on and ended up the session, and from which device (DNS name or IP address) the user logged on.

Contents:

  • RDP Connection Events in Windows Event Viewer
  • Getting Remote Desktop Login History with PowerShell
  • Outgoing RDP Connection Logs in Windows

The article is applicable when analyzing RDP logs for both Windows Server 2022/2019/2016/2012R2 and to desktop editions (Windows 11, 10, and 8.1).

RDP Connection Events in Windows Event Viewer

When a user connects to a Remote Desktop-enabled or RDS host, information about these events is stored in the Event Viewer logs (eventvwr.msc). Consider the main stages of RDP connection and related events in the Event Viewer, which may be of interest to the administrator

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

Network Connection – establishing a network connection to a server from the user’s RDP client. It is the event with the EventID 1149 (Remote Desktop Services: User authentication succeeded). If this event is found, it doesn’t mean that user authentication has been successful. This log is located in “Applications and Services Logs -> Microsoft -> Windows -> Terminal-Services-RemoteConnectionManager > Operational”. Enable the log filter for this event (right-click the log -> Filter Current Log -> EventId 1149).

windows event log Terminal-Services-RemoteConnectionManager filtering

You can list all RDP connection attempts with PowerShell:

$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

powershell script: get rdp conneciton events

Then you will get an event list with the history of all RDP connections to this server. The logs provide a username, a domain (in this case the Network Level Authentication is used; if NLA is disabled, the event description looks differently), and the IP address of the user’s computer.

EventID 1149 - Remote Desktop Services: User authentication succeeded

Authentication shows whether an RDP user has been successfully authenticated on the server or not. The log is located under Windows -> Security. So, you may be interested in the events with the EventID 4624 (An account was successfully logged on) or 4625 (An account failed to log on).

Please, pay attention to the LogonType value in the event description.

  • LogonType = 10 or 3 — if the Remote Desktop service has been used to create a new session during log on;
  • LogonType = 7, means that a user has reconnected to the existing RDP session;
  • LogonType = 5 – RDP connection to the server console (in the mstsc.exe /admin mode).

security log: rdp logon event with the username and ip adress of the remote client

In this case, the user name is contained in the event description in the Account Name field, the computer name in the Workstation Name, and the user IP in the Source Network Address.

Please, note the value of the LogonID field. This is a unique user RDP session identifier that helps track the user’s further activity. However, if an RDP session is disconnected and a user reconnects to it, the user will be assigned a new LogonID (although the RDP session remains the same).

You can get a list of successful RDP authentication events (EventID 4624) using this PowerShell command:

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

list sucess rdp auth event with an EventID 4624

Logon refers to an RDP login to Windows. EventID 21 – this event appears after a user has been successfully authenticated (Remote Desktop Services: Session logon succeeded). This events are located in the “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”. As you can see, here you can find the ID of a user RDP session — Session ID.

EventID 21 - Remote Desktop Services: Session logon succeeded

EventID – 21  (Remote Desktop Services: Shell start notification received) indicates that the Explorer shell has been successfully started (the Windows desktop appears in the user’s RDP session).

Session Disconnect/Reconnect – session disconnection and reconnection events have different IDs depending on what caused the user disconnection (disconnection due to inactivity set in timeouts for RDP sessions, Disconnect option has been selected by the user in the session, RDP session ended by another user or an administrator, etc.). You can find these events in the Event Viewer under “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”. Let’s consider the RDP Event IDs that might be useful:

  • EventID – 24 (Remote Desktop Services: Session has been disconnected) –a user has disconnected from the RDP session;
  • EventID – 25 (Remote Desktop Services: Session reconnection succeeded) – a user has reconnected to the existing RDP session on the server;
  • EventID – 39 (Session <A> has been disconnected by session <B>) – a user has disconnected from the RDP session by selecting the corresponding menu option (instead of just closing the RDP client window). If the session IDs are different, a user has been disconnected by another user (or administrator);
  • EventID – 40 (Session <A> has been disconnected, reason code <B>). Here you must check the disconnection reason code in the event description. For example:
    • reason code 0 (No additional information is available) means that a user has just closed the RDP client window;
    • reason code 5 (The client’s connection was replaced by another connection) means that a user has reconnected to the previous RDP session;
    • reason code 11 (User activity has initiated the disconnect) a user has clicked the Disconnect button in the start menu.

EventID 4778 in Windows -> Security log (A session was reconnected to a Window Station). A user has reconnected to an RDP session (a user is assigned a new LogonID).

EventID 4779 in “Windows -> Security” log (A session was disconnected from a Window Station). A user has been disconnected from an RDP session.

Logoff refers to the end of a user session. It is logged as the event with the EventID 23 (Remote Desktop Services: Session logoff succeeded) under “Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational”.

EventID 23 - Remote Desktop Services: Session logoff succeeded

At the same time the EventID 4634 (An account was logged off) appears in the Security log.

The EventID 9009  (The Desktop Window Manager has exited with code <X>) in the System log means that a user has initiated logoff from the RDP session with both the window and the graphic shell of the user have been terminated.

EventID 4647 — User-initiated logoff

Getting Remote Desktop Login History with PowerShell

Here is a short PowerShell script that lists the history of all RDP connections for the current day from the terminal RDS server event logs. The resulting table shows the connection time, the client’s IP address (DNS computername), and the remote user name (if necessary, you can include other LogonTypes in the report).

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 connection 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)"}
}
}}

powershell: list todays rdp logons with an ip and username

This method allows you to collect and parse RDP connection logs on a standalone RDSH server. If you have multiple servers in the RDS farm, you can query each of them with this script, or get logs from a management server with the Remote Desktop Connection Broker role.

You can export RDP connection logs from the Event Viewer to a CSV file (for further analysis in an Excel spreadsheet). You can export the log from the Event Viewer GUI (assuming Event Viewer logs are not cleared) or via the command prompt:

WEVTUtil query-events Security > c:psrdp_security_log.txt

Or with PowerShell:

get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:psrdp_connection_log.txt  -Encoding UTF8

If your users connect to corporate RDS hosts through the Remote Desktop Gateway, you can check the user connection logs in the Microsoft-Windows-TerminalServices-Gateway log by the EventID 302. For example, the following PowerShell script will display the specified user’s connection history through RD Gateway:

$rdpusername="b.smith"
$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

rd gateway user connection logs

You can check the following RD Gateway user connection events in the Microsoft-Windows-TerminalServices-Gateway event log:

  • 300 — The user NAME, on client computer DEVICE, met resource authorization policy requirements and was therefore authorized to connect to resource RDPHOST;
  • 302 — The user NAME, on client computer DEVICE, connected to resource RDPHOST;
  • 303 — The user NAME, on client computer DEVICE, disconnected from the following network resource: RDPHOST. Before the user disconnected, the client transferred X bytes and received X bytes. The client session duration was X seconds.

You can display the list of current remote sessions on your RDS host with the command:

qwinsta
The command returns the session ID, the USERNAME, and the session state (Active/Disconnect). This command is useful when you need to get the user’s RDP session ID when using shadow Remote Desktop connections.

Qwinsta - list RDP sessions and usernames

You can display the list of the running processes in the specific RDP session (the session ID is specified):

qprocess /id:5

qprocess - get process list for an RDP session

Outgoing RDP Connection Logs in Windows

You can also view outgoing RDP connection logs on the client side. They are available in the following event log: Application and Services Logs -> Microsoft -> Windows -> TerminalServices-ClientActiveXCore -> Microsoft-Windows-TerminalServices-RDPClient -> Operational.

For example, EventID 1102 occurs when a user connects to a remote Windows Server RDS host or a Windows 10/11 computer with RDP enabled (desktop Windows editions also support multiple simultaneous RDP connections).

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

Microsoft-Windows-TerminalServices-RDPClient connection event in Windows

The following RDP script will display the history of RDP client connections on the current computer:

$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

rdp client connection events

The script returns the SIDs of the users who initiated RDP connections on this computer, as well as the DNS names/IP addresses of the Remote Desktop hosts that the users connected to. You can convert SIDs to usernames as follows.

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

В статье не будет про серьезные вещи вроде Splunk и ELK (Elasticsearch + Logstash + Kibana). Сфокусируемся на простом и бесплатном.

Журналы и командная строка

До появления PowerShell можно было использовать такие утилиты cmd как find и findstr. Они вполне подходят для простой автоматизации. Например, когда мне понадобилось отлавливать ошибки в обмене 1С 7.7 я использовал в скриптах обмена простую команду:

findstr "Fail" *.log >> fail.txt

Она позволяла получить в файле fail.txt все ошибки обмена. Но если было нужно что-то большее, вроде получения информации о предшествующей ошибке, то приходилось создавать монструозные скрипты с циклами for или использовать сторонние утилиты. По счастью, с появлением PowerShell эти проблемы ушли в прошлое.

Основным инструментом для работы с текстовыми журналами является командлет Get-Content, предназначенный для отображения содержимого текстового файла. Например, для вывода журнала сервиса WSUS в консоль можно использовать команду:

Get-Content -Path 'C:Program FilesUpdate ServicesLogFilesSoftwareDistribution.log' | Out-Host -Paging

Для вывода последних строк журнала существует параметр Tail, который в паре с параметром Wait позволит смотреть за журналом в режиме онлайн. Посмотрим, как идет обновление системы командой:

>Get-Content -Path "C:WindowsWindowsUpdate.log" -Tail 5 -Wait


Смотрим за ходом обновления Windows.

Если же нам нужно отловить в журналах определенные события, то поможет командлет Select-String, который позволяет отобразить только строки, подходящие под маску поиска. Посмотрим на последние блокировки Windows Firewall:

Select-String -Path "C:WindowsSystem32LogFilesFirewallpfirewall.log" -Pattern 'Drop' | Select-Object -Last 20 | Format-Table Line


Смотрим, кто пытается пролезть на наш дедик.

При необходимости посмотреть в журнале строки перед и после нужной, можно использовать параметр Context. Например, для вывода трех строк после и трех строк перед ошибкой можно использовать команду:

Select-String 'C:WindowsClusterReportsCluster.log' -Pattern ' err ' ‑Context 3

Оба полезных командлета можно объединить. Например, для вывода строк с 45 по 75 из netlogon.log поможет команда:

Get-Content 'C:Windowsdebugnetlogon.log' | Select-Object -First 30 -Skip 45

Журналы системы ведутся в формате .evtx, и для работы с ними существуют отдельные командлеты. Для работы с классическими журналами («Приложение», «Система», и т.д.) используется Get-Eventlog. Этот командлет удобен, но не позволяет работать с остальными журналами приложений и служб. Для работы с любыми журналами, включая классические, существует более универсальный вариант ― Get-WinEvent. Остановимся на нем подробнее.

Для получения списка доступных системных журналов можно выполнить следующую команду:

Get-WinEvent -ListLog *


Вывод доступных журналов и информации о них.

Для просмотра какого-то конкретного журнала нужно лишь добавить его имя. Для примера получим последние 20 записей из журнала System командой:

Get-WinEvent -LogName 'System' -MaxEvents 20


Последние записи в журнале System.

Для получения определенных событий удобнее всего использовать хэш-таблицы. Подробнее о работе с хэш-таблицами в PowerShell можно прочитать в материале Technet about_Hash_Tables.

Для примера получим все события из журнала System с кодом события 1 и 6013.

Get-WinEvent -FilterHashTable @{LogName='System';ID='1','6013'}

В случае если надо получить события определенного типа ― предупреждения или ошибки, ― нужно использовать фильтр по важности (Level). Возможны следующие значения:

  • 0 ― всегда записывать;
  • 1 ― критический;
  • 2 ― ошибка;
  • 3 ― предупреждение;
  • 4 ― информация;
  • 5 ― подробный (Verbose).

Собрать хэш-таблицу с несколькими значениями важности одной командой так просто не получится. Если мы хотим получить ошибки и предупреждения из системного журнала, можно воспользоваться дополнительной фильтрацией при помощи Where-Object:

Get-WinEvent -FilterHashtable @{LogName='system'} | Where-Object -FilterScript {($_.Level -eq 2) -or ($_.Level -eq 3)}


Ошибки и предупреждения журнала System.

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

Подробнее почитать про работу обоих командлетов для работы с системными журналами можно в документации PowerShell:

  • Get-EventLog.
  • Get-WinEvent.

PowerShell ― механизм удобный и гибкий, но требует знания синтаксиса и для сложных условий и обработки большого количества файлов потребует написания полноценных скриптов. Но есть вариант обойтись всего-лишь SQL-запросами при помощи замечательного Log Parser.

Работаем с журналами посредством запросов SQL

Утилита Log Parser появилась на свет в начале «нулевых» и с тех пор успела обзавестись официальной графической оболочкой. Тем не менее актуальности своей она не потеряла и до сих пор остается для меня одним из самых любимых инструментов для анализа логов. Загрузить утилиту можно в Центре Загрузок Microsoft, графический интерфейс к ней ― в галерее Technet. О графическом интерфейсе чуть позже, начнем с самой утилиты.

О возможностях Log Parser уже рассказывалось в материале «LogParser — привычный взгляд на непривычные вещи», поэтому я начну с конкретных примеров.

Для начала разберемся с текстовыми файлами ― например, получим список подключений по RDP, заблокированных нашим фаерволом. Для получения такой информации вполне подойдет следующий SQL-запрос:

SELECT 
 extract_token(text, 0, ' ') as date, 
 extract_token(text, 1, ' ') as time,
 extract_token(text, 2, ' ') as action, 
 extract_token(text, 4, ' ') as src-ip,  
 extract_token(text, 7, ' ') as port 
FROM 'C:WindowsSystem32LogFilesFirewallpfirewall.log' 
WHERE action='DROP' AND port='3389'
ORDER BY date,time DESC

Посмотрим на результат:


Смотрим журнал Windows Firewall.

Разумеется, с полученной таблицей можно делать все что угодно ― сортировать, группировать. Насколько хватит фантазии и знания SQL.

Log Parser также прекрасно работает с множеством других источников. Например, посмотрим откуда пользователи подключались к нашему серверу по RDP.

Работать будем с журналом TerminalServices-LocalSessionManagerOperational.

Не со всеми журналами Log Parser работает просто так ― к некоторым он не может получить доступ. В нашем случае просто скопируем журнал из %SystemRoot%System32WinevtLogsMicrosoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx в %temp%test.evtx.

Данные будем получать таким запросом:

SELECT
 timegenerated as Date, 
 extract_token(strings, 0, '|') as user,
 extract_token(strings, 2, '|') as sourceip 
FROM '%temp%test.evtx'
WHERE EventID = 21
ORDER BY Date DESC


Смотрим, кто и когда подключался к нашему серверу терминалов.

Особенно удобно использовать Log Parser для работы с большим количеством файлов журналов ― например, в IIS или Exchange. Благодаря возможностям SQL можно получать самую разную аналитическую информацию, вплоть до статистики версий IOS и Android, которые подключаются к вашему серверу.

В качестве примера посмотрим статистику количества писем по дням таким запросом:

SELECT
 TO_LOCALTIME(TO_TIMESTAMP(EXTRACT_PREFIX(TO_STRING([#Fields: date-time]),0,'T'), 'yyyy-MM-dd')) AS Date,
 COUNT(*) AS [Daily Email Traffic] 
FROM 'C:Program FilesMicrosoftExchange ServerV15TransportRolesLogsMessageTracking*.LOG'
WHERE (event-id='RECEIVE') GROUP BY Date ORDER BY Date ASC

Если в системе установлены Office Web Components, загрузить которые можно в Центре загрузки Microsoft, то на выходе можно получить красивую диаграмму.


Выполняем запрос и открываем получившуюся картинку…


Любуемся результатом.

Следует отметить, что после установки Log Parser в системе регистрируется COM-компонент MSUtil.LogQuery. Он позволяет делать запросы к движку утилиты не только через вызов LogParser.exe, но и при помощи любого другого привычного языка. В качестве примера приведу простой скрипт PowerShell, который выведет 20 наиболее объемных файлов на диске С.

$LogQuery = New-Object -ComObject "MSUtil.LogQuery"
$InputFormat = New-Object -ComObject "MSUtil.LogQuery.FileSystemInputFormat"
$InputFormat.Recurse = -1
$OutputFormat = New-Object -ComObject "MSUtil.LogQuery.CSVOutputFormat"
$SQLQuery = "SELECT Top 20 Path, Size INTO '%temp%output.csv' FROM 'C:*.*' ORDER BY Size DESC"
$LogQuery.ExecuteBatch($SQLQuery, $InputFormat, $OutputFormat)
$CSV = Import-Csv  $env:TEMP'output.csv'
$CSV | fl 
Remove-Item $env:TEMP'output.csv'
$LogQuery=$null
$InputFormat=$null
$OutputFormat=$null

Ознакомиться с документацией о работе компонента можно в материале Log Parser COM API Overview на портале SystemManager.ru.

Благодаря этой возможности для облегчения работы существует несколько утилит, представляющих из себя графическую оболочку для Log Parser. Платные рассматривать не буду, а вот бесплатную Log Parser Studio покажу.


Интерфейс Log Parser Studio.

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

Вторая особенность ― возможность экспорта запроса в скрипт PowerShell.

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


Выборка наиболее активных ящиков.

При этом можно выбрать куда больше типов журналов. Например, в «чистом» Log Parser существуют ограничения по типам входных данных, и отдельного типа для Exchange нет ― нужно самостоятельно вводить описания полей и пропуск заголовков. В Log Parser Studio нужные форматы уже готовы к использованию.

Помимо Log Parser, с логами можно работать и при помощи возможностей MS Excel, которые упоминались в материале «Excel вместо PowerShell». Но максимального удобства можно достичь, подготавливая первичный материал при помощи Log Parser с последующей обработкой его через Power Query в Excel.

Приходилось ли вам использовать какие-либо инструменты для перелопачивания логов? Поделитесь в комментариях.

Иногда возникает потребность узнать кто подключался на тот или иной сервер по RDP. 

С помощью логов которые пишет ОС Windows, можно получить информацию о том с каких IP и какие пользователи подключались к виртуальному серверу,  и когда они это делали. 

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

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

1149:  Присутствие данного кода говорить об успешной аутентификации пользователя на сервере. (Remote Desktop Services: User authentication succeeded) 
21: данный код говорить об успешном входе в систему, то-есть пользователь увидел окно рабочего стола.  (Remote Desktop Services: Session logon succeeded)
24: это событие говорить об успешном отключении от RDP (Remote Desktop Services: Session has been disconnected)
25: говорит об переподключении к RDP сессии. (Remote Desktop Services: Session reconnection succeeded) 
23: пользователь нажал Logoff  и вышел из системы (Remote Desktop Services: Session logoff succeeded )
39: пользователь лично отключился от RDP сессии (не просто закрыл RDP окно). Или его отключил другой пользователь или администратор.

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

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

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

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

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

Теперь введите нужные нам события, через запятую, 1149,39,25,24,23,21 и нажмите Ок.


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

Данные ивенты, можно посмотреть в разных разделах. Например:

EventId 1149,4624,4625 — фильтруем  в Windows Logs => Security

EventId 25,24,21,39 — фильтруем  в Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational

EventId 23 — Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operationa

Теперь вы можете самостоятельно проверить по кто и когда заходил по RDP на Ваш сервер.

RRS feed

  • Remove From My Forums
  • Question

  • HI windows,

    Recently I faced an issue regarding one of my colleagues tried to login through RDP from my computer windows 7 (host name is mine) to one of SQL server instances, and it failed. Is it possible to gather relevant into regarding the ip address he tried to
    enter and username? And FYI, auditing is not enabled

    Any help would be greatly appreciated.

    • Edited by
      Adi9032
      Friday, March 29, 2019 1:58 AM

All replies

  • Hi,

    Check the event log.

    Event Viewer>Applications and Services Logs>Microsoft>Windows>TerminalServices-LocalSessionManager>Operational.

    In the TerminalService-LocalSessionManager Operational log. Event ID 21 will provide the IP address of the incoming connection.

    There is also a «RemoteDesktopServices-RemoteDesktopSessionManager» node in the event viewer tree on the left side under «Applications and Services Logs ->
    Windows». Only the Administrator role is allowed to view the file

    Some information about Audit Other Account Logon Events

    https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/dd772704(v=ws.10)

    For failed RDP connections you should enable this policy: Computer Configuration/Policies/WindowsSettings/Security Settings/Advanced Audit Policy Configuration/AuditPolicies/Audit
    Credential Validation set to Failures.

    Regards,


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

    • Proposed as answer by
      Carl FanMicrosoft contingent staff
      Saturday, March 30, 2019 11:08 AM

  • Hi Karl,

    Many thanks for your reply.

    Regards,

    Adithya

  • Hi Adithya,

    It is my pleasure. If any further help needed, please feel free to post back.

    I am proposing previous helpful replies as «Answered». Please feel free to try it and let me know the result. If the reply is helpful, please remember to mark it as answer which can help other community members who have same questions
    and find the helpful reply quickly.


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

    • Proposed as answer by
      Carl FanMicrosoft contingent staff
      Friday, April 5, 2019 7:36 AM

Sean Bianco

March 30, 2015
Last updated on May 20, 2022

Virtual desktop infrastructure (VDI) networks can run into all kinds of problems, from network connectivity to sluggish application delivery and functionality snags. End users are not usually interested in how the technology works—they are only concerned about performance. Therefore, businesses need to ensure they don’t get hit with downtime costs and that end users have a good virtual desktop experience.

The key to successfully designing, implementing, and maintaining a high-performance infrastructure lies in effectively monitoring the health and performance of the server. Remote Desktop Protocol (RDP) logs are essential. Businesses can maintain peak efficiencies by proactively identifying issues, maintaining RDP logs, and recommending solutions. Using the right reporting tools that show a correlated picture of both virtual and physical resources is key.

How do I find the RDP logs in Event Viewer?

RDP connection logs can be viewed in the Windows Event viewer (eventvwr.msc). Since these logs contain a variety of data, it can be difficult to find the exact event you need. The basic logs that particularly interest the administrator are:

1. Network Connection

Purpose Establishment of a network connection from RDP client to server
EventID 1149
Location Applications and Services Logs -> Microsoft -> Windows -> Terminal-Services-RemoteConnectionManager > Operational
How to filter these logs Right-click a network connection log and click Filter ->Current Log – > EventID 1149
Some log contents Username, Domain (if Network Level Authentication NLA is used), IP address of the client
Purpose Indicates if a logon was attempted using explicit credentials
EventID 4648
Location Windows -> Security
How to filter these logs Right-click on a success audit log and click Filter -> Current Log -> EventID 4648
Some log contents Security ID, Account Name, Account Domain, Logon ID, Logon GUID, Target Server Name

2. Authentication

Purpose Shows if an RDP client has successfully authenticated to the server
EventID 4624 – Successful authentication
4625 – Failed authentication
Location Windows -> Security
How to filter these logs Right-click on an authentication log and click Filter ->Current Log – > EventID 4624 / 4625
Some log contents LogonType (10 for a new session, 7 for an existing RDP session), account name, source network address, workstation name

3. Logon

Purpose Refers to an RDP logon, an event that appears after a user is successfully authenticated
EventID 21
Location Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational
How to filter these logs Right-click a logon log and click Filter ->Current Log – > EventID 21
Some log contents Source network address, Session ID

4. Session Disconnect/Reconnect

Purpose Covers session connect/disconnect events due to system, network, or user events
EventID 24 – Disconnected session

25 – Reconnection succeeded

39 – Disconnected by session

40 – Disconnected because of a reason 4778 – Session reconnected to Window Station

4799 – Session disconnected from window station

Location 24, 25, 39, 40 – Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational

4778, 4799 – Windows – > Security

How to filter these logs Right-click a session disconnect/reconnect log and click Filter ->Current Log – > EventID 24/25/39/40/4778/4799
Some log contents Source network address, Session ID

5. Logoff

Purpose Covers events of a purposeful logoff
EventID 23 – Remote Desktop Services session logoff succeeded

4634 – Account logged off

9009 – Desktop Window Manager has exited with code

Location 23 – Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational

4634, 9009 – Windows – > Security

How to filter these logs Right-click a session disconnect/reconnect log and click Filter ->Current Log – > EventID 23/4634/9009
Some log contents Client’s IP Address, Connection Time, Remote User Name

6. ClientActiveX

Purpose Indicates if RDP ClientActiveX is trying to connect to a server
EventID 1024
Location Windows -> TerminalServices-ClientActiveXCore -> Application and Services Logs
How to filter these logs Right-click on an event log and click Filter-> Current Log -> EventID 1024
Some log contents Security ID, Logon GUID, Process ID, Process Name, Account Name, Account Domain

Limitations of Out-of-the-Box RDP Logs

Comprehension Difficulty

Out-of-the-box RDP logs that are visible in Event Viewer are difficult to comprehend, even to the most technical people. Windows logs contain chunks of different types of data, making forensic analysis a difficult domain to conquer.

Absence of Reports

Windows Event Viewer does not have the ability to provide RDP reports that can be used for forensic analysis.

If an event occurs, you need to go through each log to point out every situation, wasting vast amounts of time and expertise.

Getting Remote Desktop Login History with PowerShell

A Quick PowerShell Script that Provides the History of All RDP Connections for the Current Day

The connection time, the client’s IP address (DNS computername), and the remote username are all displayed in the table (if necessary, you can include other LogonTypes in the report too).

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 connection 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)"}
}
}}

On a solo RDSH server, you may use this approach to gather and interpret RDP connection logs. If your RDS farm has numerous servers, you may use this script to query each of them or use the Remote Desktop Connection Broker role to receive logs from a management server.

Parallels RAS Leverages MS SQL Reporting Services

Parallels® Remote Application Server (RAS) offers a comprehensive platform to effectively monitor and manage VDI networks from anywhere, at any time. To provide analytics for better decision-making, Parallels has introduced a reporting engine. By leveraging Microsoft SQL Reporting Services, Parallels RAS provides critical insights for administrators to identify and remove bottlenecks while improving the performance and efficiency of the system.

Reporting describes important end-user activity through Parallels RAS, including apps used, how long they were used, which devices were used to access published resources, and times when users accessed resources. By analyzing these RDP logs, you can gain a wealth of information, enabling you to provide a rich VDI experience.

To generate reports, Parallels Reporting Service and Microsoft SQL have to be installed and configured on the same machine or on a system running in the same network. Parallels RAS is then configured to communicate with the SQL Server. Using the step-by-step wizard, you can quickly install and configure Parallels Reporting Service to monitor RDP logs.

Parallels Reports: RDP Logs

Parallels RAS, the one-stop-shop for RDP logs, provides 14 types of reports that are categorized into five groups:

  • User Reports provide insights into how end-users interact with Parallels RAS. They show the sessions, devices, and operating systems used by all users globally as well as individually.
  • Group Reports provide insights into how each group interacts with Parallels RAS. This information includes sessions, devices, and operating systems used by each group.
  • Devices Reports provide insights into how devices are connected to the system. This information includes the model, manufacturer, and the number of devices used by each system. In addition, it shows the operating system and the RDP client version.
  • Server Reports provide insights into how server components interact with Parallels RAS. They include a server health and performance report.
  • Application Reports provide insights into application usage. This information includes the name of the application, usage time, and the number of times used.

There are several virtualization tools in the market, but Parallels RAS is the only solution that provides this powerful reporting engine within the standard license. Parallels RAS is a comprehensive virtual desktop and application delivery solution that enables you to effectively monitor and manage the entire infrastructure.

Check out Parallels RAS and how its reporting capabilities can be ideal for your network!

Download the Trial

 
 
 

I connect to my work PC via VPN/RDP and I would like to find a log file on my work PC that would include some information on when I used it last, from where my connection originated and how long it lasted. Where in Windows 7 would I look to find that out?

asked Apr 5, 2012 at 22:19

Darius's user avatar

1

If you look at the event viewer as the administrator there are server logs but not for login/logout as far as I know.

Please check the Event Viewer tree on the left side under «Applications and Services Logs -> Windows -> TerminalServices-*» where * is all of the logs there. I think you are most interested in the TerminalService-LocalSessionManager Operational log. Event ID 21 will provide the IP address of the incoming connection.

There is also a «RemoteDesktopServices-RemoteDesktopSessionManager» node in the event viewer tree on the left side under «Applications and Services Logs -> Windows». Only the Administrator role is allowed to view the file I believe. Please confirm and let me know if this addresses your use case.

Maybe try this for logging login/logout as well:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/aptopnode.mspx?mfr=true

Community's user avatar

answered Apr 5, 2012 at 22:42

Jarrod Wageman's user avatar

1

Look under ‘Application and Services Logs’ > ‘Microsoft’ > ‘Windows’ > ‘TerminalServices-ClientActiveXCore’ > ‘Microsoft-Windows-TerminalServices-RDPClient/Operation’ ,

This log will have events which contain the server name which the end user attempted to connect RDP into.

answered Feb 3, 2014 at 3:56

Thor N's user avatar

Thor NThor N

611 silver badge1 bronze badge

1

I can’t tell you how to check from your work machine when you established a VPN as presumably it isn’t the VPN server (?). However, if you’re using Remote Desktop Connection to control that work PC you may be able to pull the logon / logoff times from the Event Viewer.

Look in the Security logs for those. RDP logons are an Event ID 4624 but just searching for 4624 won’t work. Within the event you need the Logon Type value to be «10» and the SecurityID value to be yours. Not sure how to filter those…

answered Apr 5, 2012 at 23:10

Chris_K's user avatar

Chris_KChris_K

8,5515 gold badges31 silver badges36 bronze badges

2

I found the information in the Event Viewer under Windows Logs/Security you will see under task category logon and logoff events.

answered Jul 17, 2014 at 18:28

Howard Mitchell's user avatar

3

In your case, you need to review TerminalServices-LocalSessionManager and TerminalServices-RemoteConnectionManager logs from your computer.

You can also check an excellent third party tool called SysKit, formerly Terminal Services Log. It will generate you all sort of reports from logs and will save you a bunch of time if you want to get all of the details about RDP connections and other stuff.

Please note: I am affiliated with Acceleratio, the makers of the tool mentioned above, so I might be a little bit biased here.

answered Aug 21, 2014 at 8:52

MatijaB's user avatar

2

Use the command quser to show sessions.

Then you will see something like ID 1 or 2 or 4. Then type Logoff 4 to log off that session.

You can also type query session or qwinsta (both are the same thing) Show’s who’s on and what port is listening etc.

answered Jul 3, 2016 at 15:57

Norcal Helpdesk's user avatar

Понравилась статья? Поделить с друзьями:
  • Applicationframehost exe что это за процесс windows 10
  • Application x www form urlencoded charset windows 1251
  • Application has stopped working world of tanks как исправить windows 10
  • Application hang 1002 windows 10 как исправить
  • Application hang 1002 windows 10 explorer