Notify via Email on user login with Public IP with Event ID 21 Using PowerShell script
PowerShell script for Windows Server. This script is used for fire and Email notification on any user login via Public IP.
Steps:
1. Save the script with the name EmailNotification.ps1.
2. Create a Basic Task via Task Scheduler. Enter Name for Task.
3. Select the Trigger option "When a specific event is logged"
4. Select option as below.
Script:
# Define the SMTP server details and user credentials
$smtpServer = "SMTP server" # SMTP.GMAIL.COM
$smtpUsername = "SMTP username"
$smtpPassword = "password for authentication"
$smtpSecurePassword = ConvertTo-SecureString -String $smtpPassword -AsPlainText -Force
$smtpCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $smtpUsername, $smtpSecurePassword
$from = "from@example.com"
$to = "to@example.com"
# Define Regex variable for Local IP range.
# This link will help you: https://www.analyticsmarket.com/freetools/ipregex
$lan = "^192\.168\.10\.([1-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-4])$" # LOCAL LAN
$logName = "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational"
$sourceName = "Microsoft-Windows-TerminalServices-LocalSessionManager"
$event = Get-WinEvent -LogName $logName -FilterXPath "*[System[(EventID=21) and Provider[@Name='$sourceName']]]" -MaxEvents 1
$message = $event.Message
# Extract the important details from the event
$Username = $event.Properties[0].Value
$SessionID = $event.Properties[1].Value
$datetime = $event.TimeCreated.ToString("yyyy-MM-dd hh:mm:ss tt")
$ipAddress = [IPAddress]([regex]::Matches($message, "\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b").Value)
If ($ipAddress -match $lan)
{
Write-Output "User login with Local IP"
}
Else
{
Write-Output "User login with Public IP"
$body = "<b>User Login Sucessful on Host:</b> $env:COMPUTERNAME<br>`r`n<b>User Name:</b> $Username<br>`r`n<b>Session ID:</b> $SessionID<br>`r`n<b>IP Address:</b> $ipAddress<br>`r`n<b>Date & Time:</b> $datetime<br>"
Send-MailMessage -From $from -To $to -Subject "User $Username Loggedin with External IP $ipAddress" -Body $body -BodyAsHtml -SmtpServer $smtpServer -Credential $smtpCredential
}
Post your review in a comment.
Comments