Tuesday, 3 May 2016

Account Lockout Notifications using PowerShell


This is a short and simple PowerShell script to alert an administrative mailbox, group mailbox or even the account in question that its account has locked out.

To setup the process, take the code below, adjust accordingly and save to your PDC, the DC your lockouts will always hit.

In the format below the script will send an email to $MailTo, from $MailFrom with a subject of $MailSubject via mail server $SMTPServer on port $SMTPPort.
The content of the email is held within $MailBody.

Items in bold should be correctly configured.

       

Import-Module ActiveDirectory

$AccountLockOutEvent=Get-EventLog -LogName "Security" -InstanceID 4740 -Newest 1
$LockedAccount = $($AccountLockOutEvent.ReplacementStrings[0])
$AccountLockOutEventTime = $AccountLockOutEvent.TimeGenerated
$AccountLockOutEventMessage = $AccountLockOutEvent.Message

$ADUserDisplayName = (Get-ADUser $LockedAccount -Properties DisplayName).DisplayName

$MailFrom = "AccountLockout@company.co"
$MailTo = "SomeUser@company.co"
$SMTPServer = "mailserver.company.local"
$SMTPPort = "25"
$MailSubject = "User Account Locked Out: $LockedAccount / $ADUserDisplayName" 
$MailBody = "Account $LockedAccount was locked out on $AccountLockOutEventTime.`n`nEvent Details:`n`n$AccountLockOutEventMessage`n`nUser: $ADUserDisplayName"

$EmailMessage = New-Object System.Net.Mail.MailMessage($MailFrom , $MailTo)
$emailMessage.Subject = $Mailsubject
$emailMessage.Body = $Mailbody

$SmtpClient = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
$SmtpClient.Send($emailMessage)

       
 


The second and final step is to configure a scheduled task to run when a 4740 error (Account Locked Out) is logged to the security event log.

The parameters for my scheduled task are as follows:


General
- Name: Account Lockout Email
- Run whether user is logged on or not

Triggers
Begin the task: On an event
Settings - Basic
Log: Security 
Source: Microsoft Windows security audting.
Event ID: 4740
Enabled: True

Actions
Action: Start a program

Settings
Program/script: powershell.exe
Add arguments (optional): -nologo -File "C:\Scripts\EmailOnLockout.ps1"




No comments:

Post a Comment

PerfC Vaccination for ExPetr/Petya/NotPetya Wiper

This is a script I've written to 'vaccinate' our domain against the ExPetr/Petya/NotPetya Wiper. In short, it finds all comput...