I’ve had a few issues with contractors logging directly into server, rather than using remote management tools. This script requires a scheduled tasks with a number of event triggers depending on what you want to alert on. I’m not too fussed when they log off or disconnect, but I do care seeing when they login or reconnect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<# .Name RDP_Connected.ps1 .DESCRIPTION Powershell script that sends an email when someone RDP's to a Win2012 server. .PARAMETERS None. .Version 0.1 .Author Kyle McDonald .Compatibility Windows 2008 R2 and higher .Release Date July 2015 .NOTES Create a scheduled task based on the following two triggers; - Trigger 1: When a specific event is logged --- Log: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational --- Source: TerminalServices-LocalSessionManager --- Event ID: 21 - Trigger 2: When a specific event is logged --- Log: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational --- Source: TerminalServices-LocalSessionManager --- Event ID: 25 Event IDs Descriptions; - ID 21: Session logon succeeded - ID 23: Session logoff succeeded - ID 24: Session has been disconnected - ID 25: Session reconnection succeeded #> # Get hostname $hostname = $env:computername $DomainName = $env:userdnsdomain # Get all logon/logoff events # $rdp_message = Get-WinEvent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | where {($_.Id -eq "21" -OR $_.Id -eq "24" -OR $_.Id -eq "25" -OR $_.Id -eq "23")} | select -first 1 | ft TimeCreated,Message -auto -wrap | Out-String # Get only logon and reconnections $rdp_message = Get-WinEvent -logname "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" | where {($_.Id -eq "21" -OR $_.Id -eq "25")} | select -first 1 | ft TimeCreated,Message -auto -wrap | Out-String # Configure email. $SMTPserver = "mail.contoso.com" $From = "$hostname@$DomainName" $Subject = "Someone RDPd into $hostname!" $body = $rdp_message $message = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $message.IsBodyHtml = $True $smtp = new-object Net.Mail.SmtpClient($smtpserver) $smtp.Send($message) |