В этой статье мы рассмотрим, как получить и проанализировать логи 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.
- Network Connection
- Authentication
- Logon
- Session Disconnect/Reconnect
- 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).
С помощью 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 подключений к данному серверу. В событии содержится имя пользователя, домен (если используется NLA аутентификация, при отключенном NLA текст события выглядит иначе) и IP адрес компьютера пользователя.
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 скриптом (см. статью).
При этом имя пользователя содержится в описании события в поле 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
Logon: – RDP вход в систему, EventID – 21 (Remote Desktop Services: Session logon succeeded. Это событие появляется после успешной аутентификации пользователя. Этот журнал находится в разделе Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Как вы видите, здесь можно узнать идентификатор RDP сессии для пользователя — Session ID.
Событие с 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).
При этом в журнале 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).*\s\sAccount Name:\s+([^\s]+)\s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*\s\sAccount 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 подключений из журнала в CSV файл (для дальнейшего анализа в таблице Excel). Экспорт журнала можно выполнить из консоли Event Viewer (при условии что логи не очищены) или через командную строку:
WEVTUtil query-events Security > c:\ps\security_log.txt
Или с помощью PowerShell:
get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:\ps\rdp-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
Другие события, связанные с подключениями пользователей на 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 сессии пользователя при теневом подключении.
Список запущенных процессов в конкретной RDP сессии (указывается ID сессии):
qprocess /id:157
Логи 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.
Следующий 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
Скрипт возвращает SID пользователей, которые инициировали RDP подключения на этом компьютере и DNS имена/IP адреса серверов, к которым подключались пользователи. Вы можете преобразовать SID в имена пользователей.
Также история RDP подключений пользователя хранится в реестре.
Как узнать кто подключался на тот или иной сервер по 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 на Ваш сервер.
In this article we will take a look at the features of Remote Desktop Protocol (RDP) connection auditing and log analysis in Windows. Typically, it is useful when investigating various incidents on Windows servers when a system administrator is required to provide information about what users logged on to the server, when he logged on and off, and from which device (name or IP address) the RDP user was connecting.
Remote Desktop Connection Events
Like other events, the Windows RDP connection logs are stored in the event logs. The Windows logs contain a lot of information, but it can be difficult to find the right event quickly. When a user remotely connects to a Windows server, many events are generated in the Windows logs. We will take a look at the following:
- Network Connection
- Authentication
- Logon
- Session Disconnect/Reconnect
- Logoff
Network Connection Events
Network Connection connects user’s RDP client with the Windows server. That logs EventID – 1149 (Remote Desktop Services: User authentication succeeded). The presence of this event does not indicate successful user authentication. This log can be found at Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ Terminal-Services-RemoteConnectionManager ⇒ Operational. You can filter this log by right clicking on Operational log ⇒ Selecting “Filter Current Log” and type in EventID 1149.
The result is a list with the history of all network RDP connections to this server. As you can see, the log file contains the username, domain (When Network Level Authentication (NLA) authentication is used), and IP address of the computer from which the RDP connection is made.
Authentication Events
User authentication can be successful or unsuccessful on the server. Navigate to Windows logs ⇒ Security. We are interested in logs with EventID – 4624 (An account was successfully logged on) or 4625 (An account failed to log on). Pay attention to the LogonType value in the event. LogonType – 10 or 3 indicates a new logon to the system. If LogonType is 7, it indicates re-connection to an existing RDP session.
The username of the connecting account is written in the Account Name field, his computer name is written in Workstation Name, and the IP address in Source Network Address.
Take a look at TargetLogonID field, which is a unique user session identifier that can be used to track further activity of this user. However, if a user disconnects from the RDP session and reconnects to the session again, the user will be issued a new TargetLogonID (although the RDP session remains the same).
You can get a list of successful authentication events over RDP (EventID 4624) using the following 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
Logon Events
RDP logon is the event that appears after successful user authentication. Log entry with EventID – 21 (Remote Desktop Services: Session logon succeeded). This log can be found in Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ TerminalServices-LocalSessionManager ⇒ Operational. As you can see here you can see the RDP Session ID for the user.
“Remote Desktop Services: Shell start received” details in EventID 21 means that the Explorer shell has been successfully launched in the RDP session.
Session Disconnect and Reconnect Events
Session Disconnect/Reconnect events have different codes depending on what caused the user to end the session, for example disable by inactivity, selecting “Disconnect” in Start menu, RDP session drop by another user or administrator, etc. These events can be found in Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ TerminalServices-LocalSessionManager ⇒ Operational. Let’s take a look at the RDP events that may be of interest:
- EventID – 24 (Remote Desktop Services: Session has been disconnected) – the user has disconnected from the RDP session.
- EventID – 25 (Remote Desktop Services: Session reconnection succeeded) – The user has reconnected to his existing RDP session on the server.
- EventID – 39 (Session A has been disconnected by session B) – user disconnected from his RDP session by selecting the appropriate menu item (not just closed the RDP client window by clicking on “x” in the top right corner). If the session IDs are different, then the user has been disconnected by another user or administrator.
- EventID – 40 (Session A has been disconnected, reason code B). Here you should look at the reason code for the disconnection in the event. For example:
- Reason code 0 (No additional information is available) – usually indicates that the user just closed the RDP client window.
- Reason code 5 (The client’s connection was replaced by another connection) – the user re-connected to his old session.
- Reason code 11 (User activity has the disconnect) – the user clicked the Disconnect button on the menu.
- EventID – 4778 in Windows log ⇒ Security (A session was reconnected to a Window Station). The user re-connected to an RDP session (the user is given a new LogonID).
- EventID 4799 in Windows Logon ⇒ Security (A session was reconnected to a Window Station). Disconnection from an RDP session.
Logoff Events
Logoff logs track the user disconnection from the system. In the Applications and Services Logs ⇒ Microsoft ⇒ Windows ⇒ TerminalServices-LocalSessionManager ⇒ Operational logs we can find EventID 23. In this case in Security log we need to search for EventID 4634 (An account was logged off).
Event 9009 (The Desktop Window Manager has exited with code (x)) in the System log shows that the user initiated the end of the RDP session and the user’s window and graphical shell were terminated. Below is a small PowerShell that uploads the history of all RDP connections for the current day from the Remote Desktop Service server. The table below shows the connection time, client IP address, and RDP username (you can include other logon types in the report if necessary).
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).*Account Name:\s+([^\s]+)\s+.*','$1' UserDomain = $_.Message -replace '(?smi).*Account 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)"} } }}
Exporting RDP logs
Sometimes it is needed to export RDP logs into Excel table, in this case you can upload any Windows log to a text file and afterwards import it into Excel. You can export the log from the Event Viewer console or from the command line:
WEVTUtil query-events Security > c:\ps\security_log.txt
Or:
get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:\ps\rdp-log.txt -Encoding UTF8
A list of the current RDP sessions on the server can be displayed as a command “Qwinsta”
The command returns as session identifier, username and status (Active/Disconnect). This command is useful when you need to determine the RDP session ID of a user during a shadow connection.
After defining a Session ID you can list running processes in a particular RDP session:
So here are the most common ways to view RDP connection logs in Windows.
In this article, we’ll describe how to get and audit the RDP connection logs in Windows. The RDP connection logs allow RDS terminal server 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 and desktop editions (Windows 11 and 10).
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
- Network Connection;
- Authentication;
- Logon;
- Session Disconnect/Reconnect;
- 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).
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
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.
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).
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
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
). These 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: 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.
- reason code 0 (
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”.
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).*\s\sAccount Name:\s+([^\s]+)\s+.*','$1'
UserDomain = $_.Message -replace '(?smi).*\s\sAccount 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)"}
}
}}
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:\ps\rdp_security_log.txt
Or with PowerShell:
get-winevent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | Export-Csv c:\ps\rdp_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
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 the 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.
You can display the list of the running processes in the specific RDP session (the session ID is specified):
qprocess /id:5
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.
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
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.
Remote Desktop Protocol, i.e., RDP is a particularly common protocol used to manage the remote windows servers. Administrators often require the guide to check out the user’s activity, such as when the user logged in, authenticated using which IP address, etc. This article will guide you through the step-by-step procedure for tracking and analyzing remote desktop connection logs in the windows server. In short, track & Analyze Remote Desktop Connection Logs in Windows Server
All the logins that occurred on the RDP are logged as events, and each event has an Event ID through which you can determine the actions. RDP connection logs you can view through Event Log Viewer (eventvwr.msc), and understand the reports better, we will split the article into several events and every particular event is assigned with Event ID ,
Network Connection, Authentication, Logon, Session Disconnect/Reconnect, Logoff.
First, login to Windows → Search and Open Event Log Viewer (eventvwr.msc).
Network Connection
Network connection occurred when a particular user tried to establish a network connection to the remote desktop protocol. Event ID for network connection is 1149 when user authentication succeeds. Generally, authentication success is considered a particular user logged correctly in, but in this case the specific user tries to establish a Network Connection.
Network connection logs you can find at: Event Viewer → Applications and Services Logs → Microsoft → Windows → Terminal-Services-RemoteConnectionManager → Operational.
To find the Network Connection Event ID: Click on Filter Current Log → Enter the Event ID 1149 → Click on OK.
Now, double-click on any of the entry to check the proper details,
Authentication
Here comes the second part, Authentication. This is the second factor logged in the logs where user authentication is shown with two Event IDs,
- Successful authentication Event ID (where the user logged into the RDP successful): 4624
- Un-successful authentication Event ID (where the user failed to log into the RDP successful): 4625
Furthermore, there are again three Logon types,
- Logon type 5: User authenticated to RDP server console, i.e., mstsc.exe /admin mode.
- Logon type 7: User re-connected to the existing RDP session.
- Logon type 10 or 3: The user tries to create another RDP session while already logged into the RDP.
All the authentication logs you can find at: Event Log Viewer → Windows Logs → Security.
To find the Network Connection Event IDs: Click on Filter Current Log → Enter the Event ID 4624 or 4625 → Click on OK.
Now, double-click on any of the entries to check the proper details,
Logon
Logon Event IDs will be logged when a user successfully authenticated in the RDP (Remote Desktop Services: Session logon succeeded). The Event ID for the Logon is 21. You can find the Logon logs at Event Log Viewer → Windows → TerminalServices-LocalSessionManager → Operational.
To find the Network Connection Event IDs: Click on Filter Current Log → Enter the Event ID 21 → Click on OK.
Now, double-click on any of the entries to check the proper details,
Session Disconnect/Reconnect
Session disconnection and reconnection have various reasons. Every reason for disconnection and reconnection shares different event IDs.
Event ID 24 (Remote Desktop Services: Session has been disconnected): User has disconnected from the RDP session;
Event ID 25 (Remote Desktop Services: Session reconnection succeeded): User has reconnected to the existing RDP session on the server;
Event ID 39 (Session <X> has been disconnected by session <Z>): 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).
Event ID 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) User has just closed the RDP client window.
- Reason code 5 (The client’s connection was replaced by another connection) User has reconnected to the previous RDP session.
- Reason code 11 (User activity has initiated the disconnect) User has clicked the Disconnect button in the start menu.
Event ID 4778: User re-connected to RDP session.
Event ID 4779: User disconnected from RDP session.
You can find the Session Disconnect/Reconnect logs at Event Log Viewer → Windows → TerminalServices-LocalSessionManager → Operational.
To find the Network Connection Event IDs: Click on Filter Current Log → Enter the Event ID → Click on OK.
Now, double-click on any of the entries to check the proper details,
Logoff
Here comes the last event, which gets logged that helps us when the user ends the session. Logoff shares Event ID 23. Also, you could fine Event ID 4634 (An account was logged off), Event ID 9009 (The Desktop Window Manager has exited with code), Event ID 4647 (User-initiated logoff) and you can find the logs at
Event Log Viewer → Applications and Services Logs → Microsoft → Windows → Terminal-Services-RemoteConnectionManager → Operational.
To find the Network Connection Event IDs: Click on Filter Current Log → Enter the Event ID → Click on OK.
Now, double-click on any of the entries to check the proper details,