Просмотр и анализ логов RDP подключений в Windows
В этой статье мы рассмотрим, особенности аудита / анализа логов RDP подключений в Windows. Как правило, описанные методы могут пригодиться при расследовании различных инцидентов на терминальных / RDS серверах Windows, когда от системного администратора требуется предоставить информацию: какие пользователи входили на RDS сервер, когда авторизовался и завершил сеанс конкретный пользователь, откуда / с какого устройства (имя или IP адрес) подключался RDP-пользователь. Я думаю, эта информация будет полезна как для администраторов корпоративных RDS ферм, так и владельцам RDP серверов в интернете (Windows VPS как оказалось довольно популярны).
Как и другие события, логи RDP подключения в Windows хранятся в журналах событий. Откройте консоль журнала событий (Event Viewer). Есть несколько различных журналов, в которых можно найти информацию, касающуюся RDP подключения.
В журналах Windows содержится большое количество информации, но быстро найти нужное событие бывает довольно сложно. Когда пользователь удаленно подключается к RDS серверу или удаленному столу (RDP) в журналах Windows генерируется много событий. Мы рассмотрим журналы и события на основных этапах RDP подключения, которые могут быть интересны администратору:
- 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).
В результате у вас получится список с историей всех сетевых RDP подключений к данному серверу. Как вы видите, в логах указывается имя пользователя, домен (используется NLA аутентификация, при отключенном NLA текст события выглядит иначе) и IP адрес компьютера, с которого осуществляется RDP подключение.
Authentication: – успешная или неуспешная аутентификация пользователя на сервере. Журнал Windows -> Security. Соответственно нас могут интересовать события с EventID – 4624 (успешная аутентификация — An account was successfully logged on) или 4625 (ошибка аутентификации — An account failed to log on). Обратите внимание на значение LogonType в событии. При входе через терминальную службу RDP — LogonType = 10 или 3. Если LogonType = 7, значит выполнено переподключение к уже имеющейся RDP сессии.
При этом имя пользователя содержится в описании события в поле Account Name, имя компьютера в Workstation Name, а имя пользователя в Source Network Address.
Вы можете получить список событий успешных авторизаций по 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 – события отключения / переподключения к сессии имеют разные коды в зависимости от того, что вызвало отключение пользователя (отключение по неактивности, выбор пункта Disconnect в сессии, завершение RDP сессии другим пользователем или администратором и т.д.). Эти события находятся в разделе журналов Applications and Services Logs -> Microsoft -> Windows -> TerminalServices-LocalSessionManager -> Operational. Рассмотрим RDP события, которые могут быть интересными:
Событие с EventID – 4778 в журнале Windows -> Security (A session was reconnected to a Window Station). Пользователь переподключился к RDP сессии (пользователю выдается новый LogonID).
Событие с EventID 4799 в журнале 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 ( ) в журнале System говорит о том, что пользователь инициировал завершение RDP сессии, и окно и графический shell пользователя был завершен.
Ниже представлен небольшой PowerShell, который выгружает из журналов терминального RDS сервера историю всех RDP подключений за текущий день. В полученной таблице указано время подключения, IP адрес клиента и имя RDP пользователя (при необходимости вы можете включить в отчет другие типы входов).
Иногда бывает удобно с логами в таблице Excel, в этом случае вы можете выгрузить любой журнал Windows в текстовый файл и импортировать в Excel. Экспорт журнала можно выполнить из консоли Event Viewer (конечно, при условии что логи не очищены) или через командную строку:
WEVTUtil query-events Security > c:\ps\security_log.txt
get-winevent -logname «Microsoft-Windows-TerminalServices-LocalSessionManager/Operational» | Export-Csv c:\ps\rdp-log.txt -Encoding UTF8
Список текущих RDP сессий на сервере можно вывести командой:
Команда возвращает как идентификатор сессии (ID), имя пользователя (USERNAME)и состояние (Active/Disconnect). Эту команду удобна использовать, когда нужно определить ID RDP сессии пользователя при теневом подключении.
Список запущенных процессов в конкретной RDP сессии (указывается ID сессии):
На RDP-клиенте логи не такие информационные, основное чем часто пользуются информация об истории RDP подключений в реестре.
Log off a disconnected user remotely
How do I log a disconnected user off remotely?
For example, I remotely connect to a computer (with Dameware, if that matters) and run a command that takes a significant amount of time to complete. In that time I move on to other things. When I come back, (the command has presumably completed successfully) another user has switched to their account, leaving my account status as «Disconnected». How can I remotely log off my account without having to take control of the computer, switch to my account, log off, and have the user log in again?
6 Answers 6
First, check the session number with qwinsta :
Write down the session ID.
Then use the logoff command:
See if that works.
[Edit] You can limit the query so it only shows the session id for the user that you want to log off.
In order to do that you the username name to the command, like: QWINSTA /server:YOURCOMPUTERNAMEHERE USER
Remotely logoff a user by username in one command:
I believe you can do this with logoff from the command line (assuming the machine you’re remoting into is Windows). If I understand your question correctly, a user logs in while you’re away from your remote session and logs in under a different account. You will be able to log off from their account via cmd.
If you have PSTOOLS installed, this is SUPER easy. If you do not have PSTOOLS installed, please do so. You may want to copy all of the .exes to your C:\Windows\system32 directory. (in all fairness, if you don’t have PS tools and you’re a systemadmin. you don’t know what you are missing!)
Now, run CMD.exe as an administrator on the local PC, input your admin credentials if/when prompted. Now type «psexec \\hostname cmd.exe» This command will run CMD.exe as your account, remotely, as if you are actually at the machine. In the title bar of the command prompt, you will see the remote host name called out when you have successfully connected.
Now type «query session». this will now print out all the sessions that are available active/inactive, you’ll want to note the Session ID #.
now type in «logoff #» where # = the session id you took note of previously.
You could do this with home based network PCs, but you’ll have to have the same account on BOTH systems, and it could get a little tricky.
This will DEFINITELY work with domain PCs as I have tested it several times now.
How to find a logged-in user remotely using PowerShell
- Create a certificate-signed RDP shortcut via Group Policy — Fri, Aug 9 2019
- Monitor web server uptime with a PowerShell script — Tue, Aug 6 2019
- How to build a PowerShell inventory script for Windows Servers — Fri, Aug 2 2019
A Windows admin might need this information to create reports, to track down malware infection or to see who’s in the office. Since this is a repeatable task, it’s a good idea to build a script that you can reuse over and over again, rather than having to figure out how to do it every time.
In this article, I’m going to go over how to build a PowerShell script to find a logged-on user on your local Windows machine, as well as on many different remote Windows machines at once. By the end, you should have a good understanding of what it takes to query the logged-on user of a Windows computer. You will also understand how to build a PowerShell script to execute the command on multiple computers at the same time.
With PowerShell, getting the account information for a logged-on user of a Windows machine is easy, since the username is readily available using the Win32_ComputerSystem WMI instance. This can be retrieved via PowerShell by using either the Get-CimInstance or Get-WmiObject cmdlet. I prefer to use the older Get-WmiObject cmdlet because I’m still working on older machines.
3 Ways to Remotely View Who Is Logged On
As a Windows systems administrator, there are plenty of situations where you need to remotely view who is logged on to a given computer. Many times you not only need to check who is logged on interactively at the console, but also check who is connected remotely via a Remote Desktop Connection (RDP). Fortunately Windows provides a way to do this. In fact, there are at least three ways to remotely view who’s logged on.
Each of these methods for remotely viewing who is logged on to a Windows machine assumes your Windows login has sufficient permission to connect remotely to the machine. It’s also worth pointing out that each of these ways is non-invasive. This means you can use them to check on the given machine remotely without impacting any of the users currently logged on to the remote machine.
Remote Desktop Services Manager
The Remote Desktop Services Manager is part of the Remote Server Administration Tools (RSAT) suite of tools, so you’ll need to install RSAT before you can use the Remote Desktop Manager. We also touched on the Remote Desktop Services Manager in our article about how to manage remote desktop connections.
After you have RSAT installed with the “Remote Desktop Services Tools” option enabled, you’ll find the Remote Desktop Services Manager in your Start Menu, under Administrative Tools, then Remote Desktop Services:
Once the Remote Desktop Services Manager MMC is up and running, simply right click on the “Remote Desktop Services Manager” root node in the left pane tree view:
Then when prompted, enter the hostname of the remote computer you want to view. After the MMC connects to the remote computer, you’ll see a list of users logged on to the machine and which session they’re each using:
PsLoggedOn
If you’ve read some of our previous articles you know that we’re big fans of the SysInternals suite of system utilities. Included in the PsTools set of utilities is a handy little command line app, PsLoggedOn.
As with other SysInternals tools, you’ll need to download psloggedon.exe and place it somewhere accessible on your local computer (not the remote computer), for example, in C:\PsTools.
Then, open a command prompt on your local machine and from any directory execute: C:\PsTools\psloggedon.exe \\server-a
This of course assumes you put psloggedon.exe in C:\PsTools on your local machine, and replace “server-a” with the hostname of the computer you want to remotely view who is logged on.
Query
Last but not least, there’s the built-in Windows command, “query”, located at %SystemRoot%\system32\query.exe.
Just open a command prompt and execute: query user /server:server-a
As usual, replace “server-a” with the hostname of the computer you want to remotely view who is logged on.
For more information on the query command see http://support.microsoft.com/kb/186592
As you can see there are at least three ways to get the information you need to remotely view who is logged on in a totally non-intrusive way.