История подключений по rdp windows

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

Можно экспортировать логи 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

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

1.

Start → Administrative tools → Event Viewer

Пуск → Администрирование → Просмотр событий

2.

Applications and Services Logs → Microsoft → Windows

Журналы приложений и служб → Microsoft → Windows

3.

TerminalServices-LocalSessionManager → Operational

Actions → Filter Current Log

Справа Действия → Фильтр текущего журнала

4.

Указываем код события 21 и 25

5.

Пример

EOM

Сайт rtfm.wiki использует cookies и трекинг посещений. Продолжая использовать этот сайт, вы соглашаетесь с сохранением файлов cookie на вашем компьютере. Если вы не согласны покиньте сайт или включите Adblock 😎 Что такое cookies? 🍪

Вопрос следующий, у нас есть виртуалка на которой стоит Windows Server, с Remote Desktop Protocol.
Вопрос: Где хранится история подключений к RDP ? Только в Server Manager? либо где то еще? можно ли например достать список подключавшихся к RDP айпи, на уровне провайдера который обслуживает данный VDS? Интересуют все места хранения истории подключений возможные, так же какой именно обмен информации происходит при подключении к RDP кроме айпи и времени соединения?


  • Вопрос задан

  • 42551 просмотр

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).*\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)"}
}
}}

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:\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

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.

RDPПри использовании встроенного клиента подключений через удалённый рабочий стол (mstsc.exe) нужно быть готовым к тому, что Windows сохраняет историю подключений. Сохраняются имя или IP-адрес удалённого устройства и имя пользователя, под которым было осуществлено подключение. Иногда это может приводить к глюкам операционной системы. Впрочем, и без последних иногда возникает необходимость очистить историю RDP-подключений.

К примеру, Вы подключаетесь по RDP с общедоступного компьютера. Не лучшая мысль, но иногда так складываются обстоятельства. Информация о подключениях хранится в реестре Windows отдельно для каждого пользователя. Таким образом, если пользователь не обладает правами администратора в системе, историю чужих подключений он не посмотрит. А вот администратор может посмотреть чужие подключения.

Очистка истории подключений через RDP

Итак, посмотрим, что у нас в реестре. Откройте реестр Windows командой regedit. Можно вбить в командной строке или через ПускВыполнить.

Нас интересует ветка HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client. Обратим внимание на подразделы Default и Servers. Первый хранит информацию о 10 последних подключениях, а второй содержит в себе перечень всех удалённых устройств и имён пользователей, которые использовались для подключения по RDP.

Зайдя в HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default, вы увидите десять ключей реестра с именами от MRU0 по MRU9 (Most Recently Used). Удалите их, чтобы очистить историю подключений по RDP.

Как очистить историю подключений через RDP в Windows

Если развернуть HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers, то можно увидеть перечень хостов, к которым ранее подключались под текущим пользователем. Интересны ключи UsernameHint и CertHash. Это имя пользователя, которое ранее использовалось для подключения к хосту, и отпечаток RDP-сертификата сервера. Имя пользователя из UsernameHint будет подставлено при следующей попытке подключения к удалённому компьютеру.

Как очистить историю подключений через RDP в Windows

Удалите содержимое ветки HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers. Если подразделов там много, можно удалить раздел Servers целиком, а потом создать новый пустой с таким же именем.

Далее необходимо удалить файл Default.rdp из каталога Документы текущего пользователя. Файл является скрытым, поэтому предварительно нужно включить отображений скрытых файлов и папок.

Как очистить историю подключений через RDP в Windows

Но и это ещё не всё. Информацию о последних RDP-сессиях Windows хранит ещё и в списках быстрого перехода (jump lists). Если набрать в поисковой строке «mstsc», то можно будет увидеть совершённые ранее подключения. Чтобы отключить ведение истории, откройте в реестре ветку HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced, найдите там ключ Start_TrackDocs (или создайте, если ключ отсутствует) и задайте ему значение 0 (тип DWORD). Для очистки уже существующих списков, нужно удалить файлы в каталоге %AppData%\Microsoft\Windows\Recent\AutomaticDestinations.

Вышеописанные действия можно автоматизировать. Ниже пример скрипта:

@echo off
reg delete "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default" /va /f
reg delete "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers" /f
reg add "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers"
attrib -s -h %userprofile%\documents\Default.rdp
del %userprofile%\documents\Default.rdp
del /f /s /q /a %AppData%\Microsoft\Windows\Recent\AutomaticDestinations

Что делает данный скрипт?

  1. Отключение вывода информации в консоль;
  2. Очистка информации о последних 10 подключениях;
  3. Очистка информации о ранее сделанных подключениях путём пересоздания раздела Server;
  4. Убирание атрибутов Скрытый и Системный у файла Default.rdp в каталоге текущего пользователя;
  5. Удаление файла Default.rdp;
  6. Очистка списков быстрого  перехода.

Скрипт с подобной функциональностью в PowerShell будет выглядеть следующим образом:

Get-ChildItem "HKCU:\Software\Microsoft\Terminal Server Client" -Recurse | Remove-ItemProperty -Name UsernameHint -Ea 0
Remove-Item -Path 'HKCU:\Software\Microsoft\Terminal Server Client\servers' -Recurse 2>&1 | Out-Null
Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Terminal Server Client\Default' 'MR*' 2>&1 | Out-Null
$docsfoldes = [environment]::getfolderpath("mydocuments") + '\Default.rdp'
remove-item $docsfoldes -Force 2>&1 | Out-Null

Запрет на сохранение истории подключений через RDP

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

Щёлкнув правой кнопкой мыши по разделу HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client, выберите пункт Разрешения.

Как очистить историю подключений через RDP в Windows

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

Как очистить историю подключений через RDP в Windows

Отключение кэширования изображений

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

Кэш находится в папке %LOCALAPPDATA%\Microsoft\Terminal Server Client\Cache и представляет из себя файлы с расширениями bmc и bin. В них хранятся растровые изображения размером 64×64 пикселя. При помощи несложных скриптов из этих изображений можно сложить часть удалённого рабочего стола.

Как очистить историю подключений через RDP в Windows

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

Как очистить историю подключений через RDP в Windows

После всех этих манипуляций подключения к удалённому рабочему столу в Windows станут чуть приватнее.

  • История развития ос windows презентация
  • Исчез значок языка на панели задач windows 10
  • Исчез блютуз на ноутбуке windows 11
  • Исчез значок звука в windows 7
  • История развития операционной системы windows кратко