We have strict logon policy on VMware Management servers like vCenter, View connection brokers etc. We have been looking for a solution to get alerts when someone RDP to the Management Servers (all are Windows 2008/2012).
Combination of Windows Task Scheduler and PowerShell script did the tick.
1. The following Powershell script “Get-RDPUser.ps1” will get the last terminal server (RDP) session details and send e-mail to the team in HTML table format.
[crayon lang=”powershell”]
#.SYNOPSIS
# Receive e-mail alert on RDP login at windows servers
#.DESCRIPTION
# Finds the details of latest RDP session and send e-mail to the administrator(s).
#.NOTES
# Author: Sreejesh Damodaran
#.EXAMPLE
# .\Get-RDPUser
# From e-mail address
$FromAddress = “[email protected]”
# To e-mail address
$ToAddress = “[email protected]”
# SMTP server address
$SMTPAddress = “relay.pingforinfo.com”
$USERDetails = @()
$a = “
”
$Computer = hostname
quser | Select-Object -Last 1 | ForEach-Object {
$CurrentLine = $_.Trim() -Replace ‘\s+’,’ ‘ -Split ‘\s’
$HashProps = @{
UserName = $CurrentLine[0].replace(“>”,””)
ComputerName = $Computer
}
$HashProps.SessionName = $CurrentLine[1]
$HashProps.Id = $CurrentLine[2]
$HashProps.State = $CurrentLine[3]
$HashProps.LogonTime = $CurrentLine[5..7] -join ‘ ‘
$USERDetails = New-Object -TypeName PSCustomObject -Property $HashProps |
Select-Object -Property UserName,ComputerName,State,LogonTime,SessionName
$User = $USERDetails | Select -ExpandProperty UserName
$messageParameters = @{
Subject = “[vCenter RDP Event] $User LoggedIn to $Computer ”
Body = ( $USERDetails | ConvertTo-Html -Head $a |
Out-String -Width ([int]::MaxValue))
From = $FromAddress
To = $ToAddress
SmtpServer = $SMTPAddress
}
Send-MailMessage @messageParameters -BodyAsHtml
}
[/crayon]
2. The following steps will demonstrate how to trigger (launch) powershell script “Get-RDPUser.ps1” from the specific Windows Event of RDP login.
2.1 Launch “Event Viewer” and find the latest event on successful RDP login. It should be located under “Applications and Services logs/Microsoft/Windows/TerminalServices-LocalSessionManager/Operational” with Event ID 21. Once found, right-click on the event and select “Attach Task to This Event…” then use the defaults for the first couple screens of the wizard.
2.2 Create a task to “Start a Program” with the following parameters:
Program/script: PowerShell.exe
Add arguments: c:\scripts\Get-RDPUser.ps1.
2.3 Click Next.
2.4 Select “Open the Properties dialog for this task when I click finish” and select ‘Finish’. It will open properties of the task created.
3. Select “Run whether user is logged on or not” and click OK.
You should now receive email notifications whenever someone RDP into your server.