7 способов посмотреть, кто работает на сервере терминалов
25 февраля 2017
Статьи по 1С
С чего начинается администрирование пользователей на сервере терминалов?
Конечно с просмотра «Активных» или «Отключенных» сессий пользователей.
Без этой картины администрирование сервера терминалов невозможно.
Помимо статьи, записал также, и подробное видео, о том как администрировать пользователей на сервере терминалов (Новичкам смотреть обязательно!)
Конечно, данная тема также подымается и на курсе: Администратор 1С!
И так, конечно мы должны во всех подробностях видеть, что у нас происходит на сервере терминалов!
Какие процессы запущены от имени тех или иных пользователей (в т.ч. процессы 1С) их идентификаторы, id сессий пользователей, это и многое другое помогает администратору всегда быть в курсе того что происходит на сервере и соответственно всем этим управлять, и вовремя реагировать на различные ситуации.
На разных версиях Windows server администраторы по-разному решают этот вопрос.
Кто-то смотрит пользователей используя простой «Диспетчер задач» на Windows server 2012 – 2016. Некоторые используют различные команды в CMD, ну а кое-кто использует PowerShell .
Но все администраторы хотят одного:
1. Чтоб быстро посмотреть всех пользователей кто работает на сервере.
2. Чтоб это было как можно информативней.
3. Чтоб бесплатно.
Поэтому поводу решил собрать все лучшие, простые и быстрые способы которые (на мое мнение) стоит использовать.
Уверен, что многим начинающим администраторам эти способы помогут в администрировании сервера терминалов.
И так способ первый и самый простой (На Windows server 2012 R2)
1. Диспетчер задач.
«Диспетчер задач» – вкладка «Пользователи» – позволяет нам видеть пользователей, которые работают на этом сервере.
Но по умолчанию стандартный «Диспетчер задач» – вкладка «Пользователи» нам не покажет, что пользователь работает на сервере удаленно, используя RDP, хорошо, что это можно легко исправить.
Правый клик мышкой на панели «Пользователь» и в появившимся контекстном меню
ставим птичку напротив «Сеанс» а также стоит поставить и напротив «Имя клиента».
Так мы будем знать, что этот пользователь работает у нас на сервере через RDP.
Минусы данного способа здесь очевидны, чтоб смотреть пользователей мы должны находится на сервере терминалов, где собственно и запускаем «Диспетчер задач», нет возможности сделать какую-то выборку, фильтр и т.д.
2. quser
Следующий метод это использование команды quser в CMD или PowerShell.
Quser – это аналог QUERY USER (Такое сокращение позволяет выполнять команду быстрее)
Здесь все просто запускаем CMD или PowerShell и пишем команду quser
Так мы увидим всех пользователей, что работают на этом сервере.
Метод очень простой быстрый и достаточно информативный.
Он покажет Вам – Пользователя, Сеанс, его ID, Статус , Бездействие сеанса, и время входа.
Если мы хотим посмотреть только какого-то конкретного пользователя, тогда можно написать например так:
Пример:
Term01 – это логин пользователя.
Большинство системных администраторов отдают предпочтение именно этому способу.
И не только потому, что быстро, просто и т.д., но и потому что можно смотреть удаленно всех пользователей, сидя за своим ПК, где не будь в локальной сети.
И для этого достаточно ввести команду с параметром SERVER
Пример:
Если Вы хотите больше узнать о технической стороне 1С, тогда регистрируйтесь на первый бесплатный модуль курса: Администратор 1С
If you’re curious about who is currently connected to a remote desktop connection, you’ve come to the right place. There are numerous methods for determining the number of remotely connected users.
RDP, which stands for Remote Desktop Protocol, is a protocol developed and owned by Microsoft that allows a user to connect to another computer via a network connection using a graphical interface. To connect to the server, the user uses RDP client software, whereas the server uses RDP server software, which is included with the Windows Server operating system. When a client connects to a server, Windows Servers keep track of the logged-in user’s information, which we can view.
So let’s get started.
Using Task Manager
Using Task Manager, we can see a list of active remote desktop users on a Windows server. This method of checking Active User works for every version of Windows Server.
Here are the steps:
- Goto Run and type taskmgr.exe and press the Ok button
This will open Task Manager. - Just navigate to the Users tab there you will get Users currently active.
It will display a list of users currently logged in. Here, I have only logged so it is showing one user information. Also, it contains information like what application the user is using, its current status, CPU usage, and memory usage.
Here you will only be able to determine which users are using Remote Connection. If you want to know which types of connections are used to connect to the remote, simply click on any column of the list, say «Status,» then right-click on it and select «Session.» The list will then show a session column with the types of connections to remote, such as console, terminal, services, or RDP, and so on. As shown below.
Using Query User Command
With the help of the query command, we can find various information about sessionId, the number of users, session state(active/inactive) etc on the Remote Desktop Session Host Server. This command can be used to determine whether a specific user is logged in to a specific Remote Desktop Session Host Server or not.
This command will work Windows Server 2022, Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012, etc. So, this command will not work for Windows Server 2008.
Syntax:
query user [ | | ] [/server:]
Example:
It will return the following information:
- Username: Name of the User.
- sessionname: Name of the session on Remote Desktop Session Host Server. Here, I have rdp-tcp#45
- Id: This is the session ID
- STATE: This is the state of the session either active or disconnected.
- Idle Time: the number of minutes since the session’s last keystroke or mouse movement.
- LOGON Time: THis is the login time of the user at the server.
Note: You must have Full Control Authorization or special access permission to use this command.
query session
It displays information about not only active sessions but also other sessions that the server is running.
Using quser command
This is the same as the Query User command. This command will also work for Windows Server 2022, Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 only.
Syntax
quser [ | | ] [/server:]
Using qwinsta command
Query WINdows STAtion is abbreviated as qwinsta. It displays information about sessions on a Remote Desktop Session Host server. The list includes information not only about active sessions but also about other sessions that the server runs.
Syntax
qwinsta [ | | ] [/server:] [/mode] [/flow] [/connect] [/counter]
Example:
Look at the state column and you will see whether the user is active or not. You can see here User with ID 6 is active
Using Get-RDUserSession commandlet
The Get-RDUserSession cmdlet returns a list of all user sessions in a collection or in a Remote Desktop deployment. Note that this may not work in some servers like Windows R2 2012.
Import-Module RemoteDesktop Get-RDUserSession
Output:
Using WMI
Windows Management Instrumentation (WMI) is a PowerShell subsystem that provides administrators with powerful system monitoring tools.
By simply typing the following command you will know a lot:
Get-WmiObject Win32_LoggedOnUser
If you just want to know the username just type the below command:
Get-WmiObject Win32_LoggedOnUser | Select Antecedent -Unique | %{"{0}\{1}" -f $_.Antecedent.ToString().Split('"')[1],$_.Antecedent.ToString().Split('"')[3]}
Using PsLoggedOn Tools
PsTools is a small Sysinternals command-line tool that can help in the administration of local and remote systems. It aids to determine currently logged-in users in local as well as remote systems.
Because PsLoggedOn requires a logon to access the Registry of a remote system, it will show you as logged on via resource share to remote computers that you query.
Note that this tool’s command will only work for Windows Server 2008 and above.
Syntax:
psloggedon [- ] [-l] [-x] [\\computername | username]
Here,
Parameter | Description |
— | Displays the supported options as well as the units of measurement for output values. |
-l | Displays only local logins rather than both local and network resource logons. |
-x | Don’t Show Logon times. |
computername | Specifies the name of the compute for which logon information is to be displayed. |
username | PsLoggedOn searches the network for computers where that user is logged in if you specify a user name. This is useful if you don’t want a specific user to be logged in when you’re about to change their user profile configuration. |
Download
Steps to use PsLogged.
- Download PsLogged from the above link
- Extract the files
- Goto extracted links and an open the command prompt on the same location.
- Then use the syntax mentioned above.
PSLoggedOn requires the Remote Registry Service to be running on the target computer. This service is not enabled by default.
Using Remote Event Viewer
Event Viewer is a powerful Windows tool that allows you to obtain log information from both your local and remote computers.
1 Connect successfully to a remote computer
2 Press Ctrl + R and type eventvwr and press Enter. This will open eventvwr.
3 Just click on the ‘Create Custom View‘ label located at the right corner.
4 Then under Popup, select Security under ‘Event Logs‘ and type Id in as 4624 ,4647, 4779,4800 and then press Ok.
5 In the next screen give the Name of the log like ‘Remote Login History‘ and click on Ok.
6 You will get the ‘Remote Login History‘ Label under Custom Views. Click on the label ‘Remote Login History‘ you will get all login, logout, locked, unlocked event information of the remote users.
7 Click on the row of the event and detail related to that event will get displayed just below it.
How to Enable Remote Registry Service in Remote Server?
Steps for enabling remote registry service in a remote server are as follows:
- Goto the services manager.
- Look for the «Remote Registry» service.
- Double-click on the service.
- Set the «Start Type» to «Automatic,» then press the «Start» button.
- Click OK to save your settings.
Or you can simply run the following line by line in Powershell.
Set-Service RemoteRegistry –startuptype automatic –passthru
Start-Service RemoteRegistry
Set-Service is the cmdlet that can modify the StartupType, Status, Description, and Displayname properties of a service. You can start, stop, and suspend service with the help of the Set-Service cmdlet.
Here, Set-Service is looking for RemoteRegistry Service and set this service to start automatically. And -passthru indicates that if you are already running this service then ignore it else run it automatically.
Powershell Script File which displays a List of all User RDP connection
The below script will list all users’ RDP Connections History.
Steps:
- Open Text File and paste the below code.
- Save the file as .ps1
- Open Powershell and type: Powershell.exe -File file_location_path and press Enter
where file_location_path is the actual location of the file
Scripts:
$AllUser = Get-WmiObject -Class Win32_UserAccount
foreach($User in $AllUser)
{
$RegPath = «Registry::HKEY_USERS\»+$User.SID+»\Software\Microsoft\Terminal Server Client\Servers\»
Write-Host «User:»$User.Name
Write-Host «SID:»$User.SID
Write-Host «Status:»$User.Status
$QueryPath = dir $RegPath -Name -ErrorAction SilentlyContinue
If(!$?)
{
Write-Host «[!]Not logged in»
Write-Host «[*]Try to load Hive»
$File = «C:\Documents and Settings\»+$User.Name+»\NTUSER.DAT»
$Path = «HKEY_USERS\»+$User.SID
Write-Host «[+]Path:»$Path
Write-Host «[+]File:»$File
Reg load $Path $File
If(!$?)
{
Write-Host «[!]Fail to load Hive»
Write-Host «[!]No RDP Connections History»
}
Else
{
$QueryPath = dir $RegPath -Name -ErrorAction SilentlyContinue
If(!$?)
{
Write-Host «[!]No RDP Connections History»
}
Else
{
foreach($Name in $QueryPath)
{
$User = (Get-ItemProperty -Path $RegPath$Name -ErrorAction Stop).UsernameHint
Write-Host «Server:»$Name
Write-Host «User:»$User
}
}
Write-Host «[*]Try to unload Hive»
Start-Process powershell.exe -WindowStyle Hidden -ArgumentList «Reg unload $Path»
}
}
foreach($Name in $QueryPath)
{
Try
{
$User = (Get-ItemProperty -Path $RegPath$Name -ErrorAction Stop).UsernameHint
Write-Host «Server:»$Name
Write-Host «User:»$User
}
Catch
{
Write-Host «[!]No RDP Connections History»
}
}
Write-Host «———————————-»
}
Script Credits go to gstudent@3gstudent
What is happening in the above script?
Ans: To begin, use «reg load» to load the hive. Then, from «HKEY_USERS\»+$User.SID+»\Software\Microsoft\Terminal Server Client\Servers\«, read the RDP Connections History. Finally, use «reg unload» to unload the hive. To get the history of login users, data are read from the NTUSER.DAT file.
Differentiate between local and remote desktop users in the Task Manager
Here are some differences:
-
Remote users require Remote Desktop to log in, while local users are logged in directly on the computer.
-
To observe the difference, open the Task Manager and locate the Session ID column.
-
When you open the Task Manager for both local and remote users, you will find that local users have a Session ID of 0, whereas remote users have a Session ID greater than 0.
Update: This script has been updated and can be found here: Get Logged In Users Using Powershell
Time and time again we have admins in our environment that connect to a remote desktop session, do what they need to do. And instead of logging off, they simply just close the RDP session. Leaving the user logged on until the cows come home. I’ve come across this so many times in my environment (guilty of it myself) that I decided to put my Powershell abilities to work and create a script to remotely check who is logged into a server and log them off. This Powershell script gives you the option to see who is logged into a server and if you specified a username parameter it will Find Users Logged Into A Server. It works perfect for Server 2012 R2 and Server 2016.
Table Of Contents
- Prerequisites and Requirements
- Script Parameters
- Examples and Usage
- Script Code – Get Users Logged Into Windows Machines
- Log user off the entire domain
- How to run the Script
- Video Demo Of Script
Requirements
In order to run this successfully, you need to have the following:
- The Active Directory Module must be installed on the computer.
- Powershell Version 3.0 or greater.
- Run the Powershell Windows as an administrator.
The script actually will not run if the requirements are not met.
Parameters
-Computername
Description: This will specify the computername that you would like to check. If no computername is specified, it will check the local computer.
-Username
Description: This will specify a username that you would like to check. If a username is specified, it will only filter said username. The default is the currently logged on user.
-LogOff
Description: If the logoff parameter is specified, it will logoff the user from the computer.
-LogErrors
Description: If the LogErrors parameter is specified, it will log any errors that occurred during the run. The default location is the users desktop.
Examples
Example 1: The default option is to check the current user and current computer.
PS C:\> Get-UsersAndLogOffComputers Computer : PAC-WIN1001 Username : pcontreras State : Active Session : console SessionID : 2
Example 2: Specify a computername or multiple computernames seperated by a comma.
PS C:\> Get-UsersAndLogOffComputers -ComputerName PAC-FS01, PAC-SCCM01 Computer : PAC-FS01 Username : pcontreras State : Active Session : rdp-tcp#8 SessionID : 3 Computer : PAC-SCCM01 Username : pcontreras State : Disconnected Session : Idle SessionID : 3
PAC-FS01 and PAC-SCCM01 were both specified and results were outputted. As you can see PAC-FS01 has an active session and PAC-SCCM01 has an Idle session. The Idle session means someone RDP’d in and disconnected instead of logging off.
Example 3: Specify multiple computernames and a username.
PS C:\> Get-UsersAndLogOffComputers -ComputerName PAC-FS01, PAC-SCCM01 -Username DJones Computer : PAC-FS01 Username : DJones State : Active Session : console SessionID : 1
The username DJones was specified and it was found logged into PAC-FS01. PAC-SCCM01 didn’t find a match so nothing was outputted.
Example 4: Specify the username DJones and log it off the computer named PAC-FS01.
PS C:\> Get-UsersAndLogOffComputers -ComputerName PAC-FS01 -Username DJones -Logoff Computer : PAC-FS01 Username : DJones State : Active Session : console SessionID : 1
The same output will occur with the -Logoff Switch, however it will log the specified user off as long as it has admin rights to that machine.
Example 5: Log the errors (if any) to give you a better idea of what the issue is.
PS C:\> Get-UsersAndLogOffComputers -ComputerName PAC-FS01, DoesntExist -Username DJones -LogErrors
In this example I specified the computer names PAC-FS01 and DoesntExist. The username DJones doesn’t have rights to the server so the error that was logged shows Access is denied. The “Doesntexist” computer was not found and obviously not online so the error that was logged was “The RPC server is unavailable.” The default path for the error log file is going to be the users desktop.
Script To Get Users Logged Into Windows Server Remotely
Great, so now that have the parameters and the examples out of the way, let’s get to the actual script.
Function Get-UsersAndLogOffComputers { #requires -Module ActiveDirectory #requires -RunAsAdministrator #requires -Version 3.0 <# .SYNOPSIS This will check to see if a user is logged on to a server and if specified, log them off. For updated help and examples refer to -Online version. .DESCRIPTION This will check to see if a user is logged on to a server and if specified, log them off. For updated help and examples refer to -Online version. .NOTES Name: Get-UsersAndLogOffComputers Author: theSysadminChannel Version: 1.01 DateCreated: 2017-Apr-01 .LINK https://thesysadminchannel.com/find-users-logged-into-a-server-and-log-them-off-remotely/ - For updated help and examples refer to -Online version. #> [CmdletBinding()] param( [Parameter( ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string[]] $ComputerName = $env:COMPUTERNAME, [Parameter()] [string] $Username = $env:USERNAME, [Parameter()] [switch] $Logoff, [Parameter()] [switch] $LogErrors ) BEGIN { $ErrorLogFile = "$env:USERPROFILE\Desktop\Get-UsersAndLogOffComputers.txt" if (Test-Path $ErrorLogFile) {Remove-Item $ErrorLogFile} } PROCESS { Foreach ($Computer in $ComputerName) { try { $ExplorerProcess = Get-WmiObject Win32_Process -Filter "Name = 'explorer.exe'" -ComputerName $Computer -EA Stop if ($ExplorerProcess) { $ExplorerProcess = $ExplorerProcess.GetOwner().User foreach ($Person in $ExplorerProcess) { if ($Username -eq $Person) { $Session = (query session $Username /Server:$Computer | Select-String -Pattern $Username -EA Stop).ToString().Trim() $Session = $Session -replace '\s+', ' ' $Session = $Session -replace '>', '' if ($Session.Split(' ')[2] -cne "Disc") { $Properties = @{Computer = $Computer Username = $Username.Replace('{}','') Session = $Session.Split(' ')[0] SessionID = $Session.Split(' ')[2] State = $Session.Split(' ')[3] } } else { $Properties = @{Computer = $Computer Username = $Username.Replace('{}','') Session = 'Idle' SessionID = $Session.Split(' ')[1] State = 'Disconnected' } } $Object = New-Object -TypeName PSObject -Property $Properties | Select Computer, Username, State, Session, SessionID } } } } catch { $ErrorMessage = $Computer + " Error: " + $_.Exception.Message Write-Error $_.Exception.Message } finally { if ($ErrorMessage -and $LogErrors) { Write-Output $ErrorMessage | Out-File $ErrorLogFile -Append $ErrorMessage = $null } if ($Logoff -and $Object.SessionID) { LogOff.exe /server:$Computer $Object.SessionID } Write-Output $Object $Object = $null } } } END {} }
Log user off the entire domain or just all servers
Since this script allows inputs for multiple objects, we can easily pipe in an array of Servers or computers in general.
Getting all the Servers in the domain and seeing if the user DJones is logged on. Again we can use the -LogOff
parameter to log the user out. If you have more 100 or 200 hundred servers I would probably make the filter a little smaller so use with a bit of caution.
#Get all servers and enumerate through each one to see if the user is logged in. $Servers = Get-ADComputer -Filter {(OperatingSystem -like "*Server*") -and (Enabled -eq $true)} -Properties OperatingSystem | select -ExpandProperty Name | Sort-Object Get-UsersAndLogOffComputers -ComputerName $Servers -Username DJones #Get every computer object in the domain that is enabled and check to see if the user is logged in. $AllComputers = Get-ADComputer -Filter {Enabled -eq $true} | select -ExpandProperty Name | Sort-Object Get-UsersAndLogOffComputers -ComputerName $AllComputers -Username DJones
How to run the Script
In order to the run the script there are a couple of things you need to do. First and foremost, set your execution policy to RemoteSigned. This is a standard with running any powershell script.
Next you need to dot source the script since it is a function. To dot source the script do the following:
- Copy the script above and save it any location. In this example I’ll save it to my C:\_Scripts folder.
- Within the Powershell Window running as Administrator type: . .\_Scripts\Get-UsersAndLogOffComputers.ps1 – Note the two dots before the backslash.
Now you’re all set to call the function and run any of the parameters listed above.
Video and Explanation of how to Find Users Logged Into A Server
If you have any trouble dot sourcing the script or find any bugs please let me know in the comments section and I’ll be happy to update it.
If you’re looking to expand your Powershell knowledge check out Don Jones Learn Powershell In a Month Of Lunches Book and I hope this article to Find Users Logged Into A Server was informative and if you need to log user off remotely hopefully you will use this script.
habibzain Follow
Just husband, father and enthusiastic men about System Administration. Love to write short article about it. Perhaps can help and be useful for others.
39 sec read
Hi Dude, Sometimes we need to know how many users are logged in remote desktop on windows server. so how can we see it? Here are the tips to show list RDP user.
Tips to Show List RDP Users
#1: Show List User with Task Manager
Okay, tips #1 is using Task Manager. you can view how many user login Remote Dekstop using it. You can click tab “user”, and will show all of user login.
#2: Use Command Line (CMD)
Press the Windows logo key + R and type cmd and press Enter.
Type query user and press Enter. It will show list all users that are currently logged on your computer/server.
Count Active State
This my easy to count active state session RDP in server.
C:\Users\habibza>quser | find /i "Active" /c
And the last, count all session. Whether it’s active, inactive and disconnected sessions.
That is easy wat to show list user login rdp remote desktop protocol. May be it’s helpful, please feel free to leave a comment if you have any questions and I’ll appreciate it.
habibzain Follow
Just husband, father and enthusiastic men about System Administration. Love to write short article about it. Perhaps can help and be useful for others.
- #rdp
- #windows
- #windows-server