Registro de Creación de Usuarios en el Directorio Activo

Cuando el Directorio Activo es administrado por un grupo de personas, y necesitamos saber quien ha realizado o realiza alguna tarea concreta, este script nos ayuda a mantener un registro de quien/quienes crean usuarios en el Directorio Activo de nuestro dominio.

Consideraciones para la ejecución del script:

  1. Habilitar auditoria en los controladores de dominio
  2.  El evento que registra la creación de usuarios es el 4720 de la parte de seguridad del visor de eventos.
  3. Ejecutar el script en los controladores de dominio si no se tiene habilitado WMI en dichos DC.
  4. El script registra todos los usuarios que se han creado en el dia anterior.
  5. El script registra el objeto usuario que se ha creado, la fecha en la que se ha creado y el objeto que crea dicha cuenta de usuario.

Script de Powershell:

param( [switch]$LastLogonOnly,[switch]$OuOnly)
############## Find EventID 4720 with user's requesting Kerberos TGT, skipping Exchange Health Mailbox request and extracting Users/Client names,IP Addresses ####

Set-ExecutionPolicy Unrestricted -Force

#Create directorys if not exists
New-Item -ItemType Directory -Force -Path "C:\scripts" | Out-Null

New-Item -ItemType Directory -Force -Path "C:\scripts\usuariosCreados" | Out-Null

Remove-Item "C:\scripts\usuariosCreados\usuariosCreados_$((Get-Date).AddDays(-1).ToString('dd-MM-yyyy')).csv" -Force -ErrorAction SilentlyContinue

$Domain = (Get-WmiObject Win32_Computersystem).domain

$read_log={
Param ($OuOnly,$Domain) ## Define parameter to pass maxevent to scripblock
$EventInfo=Get-WinEvent -FilterHashTable @{LogName="Security"; ID=4720} | where {$_.Message -notmatch "SM_" } | where { $_.Message -notmatch "\$" } |
select Message, TimeCreated , MachineName

$EventInfo | foreach {
############# Find the User account in AD and if not found, throw and exception ###########
$Full_User_Property=0
Try ## Need Try statement to test and surpress error
{
$Full_User_Property = (Get-AdUser $_.usuario -Properties *)
$_."Localizacion" = $Full_User_Property.CanonicalName.TrimStart($Domain).SubString(1)
}
catch
{ } ## The $_."User Location" is not passed to catch statement thus needing another below statement to set value"

Return $_
}
}

########### Job starts to query replica domain controllers #############
$result=@()
$RemoteJob=@()

#Importa modulo de AD
Import-Module ActiveDirectory
$date= ((Get-Date).AddDays(-1))
$dateString = $date.ToLongDateString()

## Make array of remote jobs

$DomainControllers = (Get-ADDomainController -Filter { isGlobalCatalog -eq $true -or isGlobalCatalog -eq $false}).Name

############### Start the Local Job and Remote Job to find the event id ################
$LocalJobExists=0
If ($DomainControllers -contains $(hostname)) ## Check if the computer running the script is Domain Controller itself
{
$LocalJob = Start-Job -scriptblock $read_log -ArgumentList $OuOnly,$Domain;$LocalJobExists=1 ## If so, start job to query local domain controller
}

$DomainControllers | where {$_ -ne $(hostname)} | foreach {
## Start remote jobs on each other domain controllers
$RemoteJob+= Invoke-Command -ComputerName $_ -ScriptBlock $read_log -ArgumentList $OuOnly,$Domain -AsJob -ErrorAction SilentlyContinue
}

If ($LocalJobExists)
{
$result = $LocalJob | Wait-Job | Receive-Job; Remove-Job $LocalJob ## If the computer running the script is not a domain controller(may be RSAT installed), then all jobs will be remote jobs

}

$resultDomainController=@()
$RemoteJob | foreach {
$resultDomainController= $resultDomainController + $_ | Wait-Job -ErrorAction SilentlyContinue -Force | Receive-Job -ErrorAction SilentlyContinue;
Remove-Job $_ -ErrorAction SilentlyContinue -Force }
## Wait and Receive remote jobs on each remote DCs and add to Local job result

forEach ($a in $result){
if ($a.TimeCreated.ToLongDateString() -eq $dateString) {
#Manipulate manually message
$message = $a.message
$message | Out-File -FilePath "C:\scripts\message.txt"
$admin = Select-String C:\scripts\message.txt -pattern "Nombre de cuenta:"
$nameAdmin = $admin[0].Line.Split(":")
$user = Select-String C:\scripts\message.txt -pattern "Nombre principal de usuario:"
$nameUser = $user.Line.Split(":")
Remove-Item C:\scripts\message.txt -Force -ErrorAction SilentlyContinue

If ($LastLogonOnly)
{
$(
[PSCustomObject]@{UsuarioCreado=$nameUser[1].Trim();Administrador=$nameAdmin[1].Trim();FechayHora=$a.TimeCreated.ToShortDateString() +","+ $a.TimeCreated.ToShortTimeString();NombreMaquina=$a.MachineName}
) | Export-Csv "C:\scripts\usuariosCreados\usuariosCreados_$((Get-Date).AddDays(-1).ToString('dd-MM-yyyy')).csv" -NoTypeInformation -Append
}
else
{
$(
[PSCustomObject]@{UsuarioCreado=$nameUser[1].Trim();Administrador=$nameAdmin[1].Trim();FechayHora=$a.TimeCreated.ToShortDateString() +","+ $a.TimeCreated.ToShortTimeString();NombreMaquina=$a.MachineName}
) | Export-Csv "C:\scripts\usuariosCreados\usuariosCreados_$((Get-Date).AddDays(-1).ToString('dd-MM-yyyy')).csv" -NoTypeInformation -Append

}
}
}

forEach ($a in $resultDomainController){
if ($a.TimeCreated.ToLongDateString() -eq $dateString) {
#Manipulate manually message
$message = $a.message
$message | Out-File -FilePath "C:\scripts\message.txt"
$admin = Select-String C:\scripts\message.txt -pattern "Nombre de cuenta:"
$nameAdmin = $admin[0].Line.Split(":")
$user = Select-String C:\scripts\message.txt -pattern "Nombre principal de usuario:"
$nameUser = $user.Line.Split(":")
Remove-Item C:\scripts\message.txt -Force -ErrorAction SilentlyContinue

If ($LastLogonOnly)
{
$(
[PSCustomObject]@{UsuarioCreado=$nameUser[1].Trim();Administrador=$nameAdmin[1].Trim();FechayHora=$a.TimeCreated.ToShortDateString() +","+ $a.TimeCreated.ToShortTimeString();NombreMaquina=$a.MachineName}
) | Export-Csv "C:\scripts\usuariosCreados\usuariosCreados_$((Get-Date).AddDays(-1).ToString('dd-MM-yyyy')).csv" -NoTypeInformation -Append
}
else
{
$(
[PSCustomObject]@{UsuarioCreado=$nameUser[1].Trim();Administrador=$nameAdmin[1].Trim();FechayHora=$a.TimeCreated.ToShortDateString() +","+ $a.TimeCreated.ToShortTimeString();NombreMaquina=$a.MachineName}
) | Export-Csv "C:\scripts\usuariosCreados\usuariosCreados_$((Get-Date).AddDays(-1).ToString('dd-MM-yyyy')).csv" -NoTypeInformation -Append

}
}
}

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *