Pages

Wednesday, October 20, 2021

Query and Reset or Logoff RDP Sessions from Windows Server

Query existing RDP Sessions  on a Windows server and Reset or Log Off those sessions.

Being Windows System Admins we often find our self in situations wherein we had left existing RDP sessions in disconnected state (not logged off properly) and once our Password is changed it keeps sending bad/invalid credentials resulting in account lockouts.

The solution to this is we need to find out existing RDP Sessions and log them off by providing the Session ID.

The command to query the Sessions is

query session /server:RemoteServerName

Here is the output of this command:

PS C:\> query session /server:RemoteServerName
SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
services                                    0  Disc
console                                     1  Conn
rdp-tcp#48        My_User_Name             7  Active
rdp-tcp                                 65536  Listen
PS C:\>

The command mentioned above returns a plain text output which shows Session details which contains Session id and to reset the session we need to issue further command like below:

Command to reset the session

reset session /server:RemoteServerName 7

This will log off the session  ID 7 from the server and thus it will prevent bad/invalid credentials from being sent resulting in Acount Lockout.

I have tried to write a simple PowerShell Script which accepts two Parameters and automatically finds the session ID and resets it without us specifying the session id manually.

.\Reset-TSSessions.ps1 -UserName My_User_Name -ServerName RemoteServerName

Here is My Git Repo where this script has been hosted :

https://github.com/Prakash82x/PowerShell/blob/master/TerminalService/Reset-TSSessions.ps1

########################################################################################
## Written by Prakash Kumar to Query and reset Remote RDP Sessions on Windows Servers ##
## Usage : .\Reset-TSSessions.ps1 -UserName My_User_Name -ServerName MyServerName     ##
########################################################################################
param ($UserName,
    $ServerName)

Write-host -ForegroundColor Green `nQuerying Sessions for $UserName on $ServerName
$Sessions = qwinsta /server:$ServerName
$MySessions = $Sessions | Select-String "$UserName"
$FinalSessions = $MySessions -replace ' {2,}', ',' -split ","

if ($MySessions -match "$UserName") {
    $User = $FinalSessions[1]
    $SessionID = $FinalSessions[2]
    $SessionState = $FinalSessions[3]
    Write-host `n"UserName        SessionID        SessionState"
    Write-host "--------        ---------        ------------"
    Write-Host "$User   $SessionID                $SessionState"
    Write-host "--------        ---------        ------------"
    Write-host -ForegroundColor Red `n"Resetting Session for`t $User on $ServerName : Session ID $SessionID : SessionState $SessionState"
    rwinsta /server:$ServerName $SessionID
}

Else {
    Write-host -ForegroundColor Yellow No Sessions Exist for user $UserName on Server $ServerName

}

PS: While running this script you need to make sure you are logged in using the same user name on a server and that it has Admin rights on the destination server as well to be able to logoff the session.

Note that Qwinsta and Query Session work exactly like same commands.

Tuesday, September 14, 2021

Getting CPU Idle & CPU Utilization data from MacPro machines using Zabbix UserParameter & Zabbix Calculated Item

 Getting CPU Idle & CPU Utilization data from MacPro machines using Zabbix UserParameter & Zabbix Calculated Item

Objective : We wanted to see how much some of the Mac machines which are deployed in our Data Center are utilized in terms of CPU/Memory usage.

Approach : Being OpenSource Monitoring solution We zeroed down on Zabbix (5.4) for capturing utilization data of these Macs and hence we deployed a Zabbix appliance  (Server) and Installed Zabbix Agent on the Mac Machines from here.

Challenge : After looking at the Items supported by platform we realized that the Zabbix Agent (5.4) available for Mac does not have a metric/item out of the box which can provide CPU Utilization/Idle stats so we thought to use UserParameter option of Zabbix to get the same.

Let’s walk through the different steps we followed to capture CPU Utilization statistics from Mac machines and how it looks after that.

After connecting to the Mac remotely using ssh, we ran the following command to show what version of Mac we are running along with few other details about the system.

system_profiler SPHardwareDataType

The default template of Mac which came along with the Zabbix Appliance does not have any metric/item which collects CPU Utilization/CPU Idle metric from the Mac hence our first step would be to figure out if we can get CPU Utilization/Idle data from Mac Machines.

After browsing through different forums, we got to know that CPU Utilization/Idle value can be retrieved using following command.

top -l 1 | grep -E "^CPU"

Now we need to do some trimming with above output and get only the CPU Idle stat as a Float value and get rid of  ‘%’ and ‘idle’ strings also.

ServerName:~ admin$ top -l 1 | grep -E "^CPU" |awk -F, '{print $3}'

91.37% idle

ServerName:~ admin$ top -l 1 | grep -E "^CPU" |awk -F, '{print $3}'|awk '{print $1}'

91.93%

ServerName:~ admin$ top -l 1 | grep -E "^CPU" |awk -F, '{print $3}'|awk '{print $1}' | tr '%' ' '

91.52

ServerName:~ admin$

 

The output above is what we need to get Current CPU Idle value which we can subtract with 100 to get CPU Utilization Stat at that point in time.

There are different ways to define a UserParameter at the Zabbix Agent side and we are going to use the Default configuration file located at /usr/local/etc/zabbix/zabbix_agentd.conf to get it configured.

Let’s add following line to define a UserParamter on the monitored Mac Machine so that it starts sending the CPU Idle value to Zabbix Server.

 UserParameter=cpuidle,top -l 1 | grep -E "^CPU" |awk -F, '{print \$3}' | awk '{print \$1}' | tr '%' ' '

 I used following command on the Terminal/SSH session of the Mac machine to append above line in the Zabbix config file:

 echo "UserParameter=cpuidle,top -l 1|grep -E "^CPU"|awk -F, '{print \$3}'|awk '{print \$1}'|tr '%' ' '"|sudo tee -a /usr/local/etc/zabbix/zabbix_agentd.conf

Step 1 is the command we used to append UserParameter in the configuration file and step 2 Shows if the line has been appended in config file.

We can verify if the line has been appended in the configuration file with following command:

tail -10 /usr/local/etc/zabbix/zabbix_agentd.conf

 ** Please ensure that the Zabbix agent service is restarted after appending UserParameter line in the Zabbix Configuration file by following below steps:

sudo launchctl stop com.zabbix.zabbix_agentd

sudo launchctl start com.zabbix.zabbix_agentd

 The output above shows we are all set and ready to do the configuration on Zabbix Web Frontend.

 Let’s head over to the Zabbix Web Frontend and add a new Item to get CPU Idle Value.

Go to Configuration>Templates>MacOS and click on Create Item

Refer to the following Screenshot and fill in details accordingly.

 

 There is a Test option available at the bottom of Item Creation Window which we can use to test if we are getting values from the monitored Mac.

 

We tested the newly created item and we can see that the host is sending data (CPU Idle Value)

 Let’s go to Monitoring>Latest data and select the Mac Machine and see if we are getting CPU Idle Value.

 

 We have been able to get a custom/ UserParameter setup on Zabbix Agent Side and got the value from Mac also so, it looks all good now.

 Optionally, since we have CPU Idle value coming on Zabbix Server so we have an option to Create a Calculated Item based on CPU Idle value and populate CPU Utilization data also.

Let’s now see how a Calculated Item is created in the Same Template to show CPU Utilization Data.

Navigate to Configuration>Template>macOS and click on Create Item.

Select Following

Name                  : CPU Utilization

Type                    : Calculated

Key                       : CPU_Utilization #(Can be anything you want)

Formula               : 100-last(//cpuidle)  

 **The CPU Utilization value is (100 - CPU Idle Time) so according to that we have put that formula.

 

We can again click on Test and see if the data is being returned.

Let’s head over to Monitoring>Latest data> and see if we are getting calculate Item’s value.

 

This shows that we are getting CPU Idle and CPU Utilization data from using Zabbix agent with the help of a Custom /UserParameter and thus have successfully achieved our objective.