Category Archives: SystemIT

Using Powershell to Trace the Source of Account Lockouts in Active Directory

How to: track the source of user account lockout using Powershell

In my last post about how to Find the source of Account Lockouts in Active Directory I showed a way to filter the event viewer security log with a nifty XML query.

In this post I recomposed (Source:Ian Farr) a Powershell script which will ask for the locked user account name and then will scan the active directory DCs security log for relevant events and will present the user lock time and source of the lock out like so:

locked user powershell script

Make sure you have the active directory module loaded on the machine you run the script from: Import-Module ActiveDirectory

You can add the import-module command to the top of the script if you like.

The script:

$ErrorActionPreference = "SilentlyContinue"
Clear-Host

$User = Read-Host -Prompt "Please enter a user name"

#Locate the PDC
$PDC = (Get-ADDomainController -Discover -Service PrimaryDC).Name
#Locate all DCs
$DCs = (Get-ADDomainController -Filter *).Name #| Select-Object name

foreach ($DC in $DCs) {
Write-Host -ForegroundColor Green "Checking events on $dc for User: $user"
    if ($DC -eq $PDC) {
        Write-Host -ForegroundColor Green "$DC is the PDC"
        }
    Get-WinEvent -ComputerName $DC -Logname Security -FilterXPath "*[System[EventID=4740 or EventID=4625 or EventID=4770 or EventID=4771 and TimeCreated[timediff(@SystemTime) <= 3600000]] and EventData[Data[@Name='TargetUserName']='$User']]" | Select-Object TimeCreated,@{Name='User Name';Expression={$_.Properties[0].Value}},@{Name='Source Host';Expression={$_.Properties[1].Value}} -ErrorAction SilentlyContinue
    }

This script scans ALL Domain Controllers and not just the PDC as most people do. I found that sometimes a lockout event will appear in a different DC server, so to make sure you dont miss anything, its better in my opinion to scan all domain controllers and wait the extra time for the script to finish. However, in most cases lockout events will appear on the PDC server.

After you have found the source of user lockout, go to each PC and disconnect the session or look for running scheduled tasks or scripts under this user context.  Rebooting the locking PC if possible, is also a good practice.

Here is another script contributed by Alexandre Almeida on the same topic.

#script written by Alexandre Almeida

# for get user Account Lockout Host name

$username = Read-Host "Please Enter the Locked User Name: "
 
        $DCCounter = 0  
        $LockedOutStats = @()    
                 
        Try 
        { 
            Import-Module ActiveDirectory -ErrorAction Stop 
        } 
        Catch 
        { 
           Write-Warning $_ 
           Break 
        } 
         
        #Get all domain controllers in domain 
        $DomainControllers = Get-ADDomainController -Filter * 
        $PDCEmulator = ($DomainControllers | Where-Object {$_.OperationMasterRoles -contains "PDCEmulator"}) 
         
        Write-Verbose "Finding the domain controllers in the domain" 
        Foreach($DC in $DomainControllers) 
        { 
            # $DCCounter++ 
            # Write-Progress -Activity "Contacting DCs for lockout info" -Status "Querying $($DC.Hostname)" -PercentComplete (($DCCounter/$DomainControllers.Count) * 100) 
      Write-Verbose "Finding the Which domain controllers Authenticate the Password"
            Try 
            { 
                $UserInfo = Get-ADUser -Identity $username  -Server $DC.Hostname -Properties LastLogonDate -ErrorAction Stop 
      Write-Verbose "Bad Password Attempt count collected"
            } 
            Catch 
            { 
                # Write-Warning $_ 
                Continue 
            } 
            If($UserInfo.LastBadPasswordAttempt) 
            {     
                $LockedOutStats += New-Object -TypeName PSObject -Property @{ 
                        Name                   = $UserInfo.SamAccountName 
                        SID                    = $UserInfo.SID.Value 
                        LockedOut              = $UserInfo.LockedOut 
                        BadPwdCount            = $UserInfo.BadPwdCount 
                        BadPasswordTime        = $UserInfo.BadPasswordTime             
                        DomainController       = $DC.Hostname 
                        AccountLockoutTime     = $UserInfo.AccountLockoutTime 
                        LastLogonDate = ($UserInfo.LastLogonDate).ToLocalTime() 
                    }           
            }#end if 
        }#end foreach DCs 
        $LockedOutStats | Format-Table -Property Name,LockedOut,DomainController,BadPwdCount,AccountLockoutTime,LastBadPasswordAttempt -AutoSize 
 
        #Get User Info 
        Try 
        {   
           Write-Verbose "Querying event log on $($PDCEmulator.HostName)" 
     Write-Verbose "Collecting Event Log"
           $LockedOutEvents = Get-WinEvent -ComputerName $PDCEmulator.HostName -FilterHashtable @{LogName='Security';Id=4740} -ErrorAction Stop | Sort-Object -Property TimeCreated -Descending 
        } 
        Catch  
        {           
           Write-Warning $_ 
           Continue 
        }#end catch      
                                  
        Foreach($Event in $LockedOutEvents) 
        {             
           If($Event | Where {$_.Properties[2].value -match $UserInfo.SID.Value}) 
           {  
               
              $Event | Select-Object -Property @( 
                @{Label = 'User';               Expression = {$_.Properties[0].Value}} 
                @{Label = 'DomainController';   Expression = {$_.MachineName}} 
    @{Label = 'EventId';            Expression = {$_.Id}} 
                @{Label = 'LockedOutTimeStamp'; Expression = {$_.TimeCreated}} 
                @{Label = 'Message';            Expression = {$_.Message -split "`r" | Select -First 1}} 
                @{Label = 'LockedOutLocation';  Expression = {$_.Properties[1].Value}}
             ) 
      Write-host $_.MachineName
                                                 
            }#end ifevent 
             
       }#end foreach lockedout event
  Write-Verbose "Collected Details Update in the Text File. Please find the Text file for More Details"

echo "Cache Profile Removal Steps
1) Open Control Panel > Credential Manager > Remove all Saved Password.
2) Remove passwords by clicking on Start => Run => type (rundll32.exe keymgr.dll KRShowKeyMgr) without quotes and then delete the Domain-related passwords;
3) Remove passwords in Internet Explorer => Tools => Internet Options =>Content => Personal Information => Auto Complete => Clear Passwords;
4) Delete cookies in Internet Explorer => Tools => Internet Options =>General;
5) Disconnect (note the path before disconnecting) all networks drives, reboot, then map them again;
6) Start -> run ->type control userpasswords2 without quotes and go to advanced -> Manage passwords and remove all the stored passwords.
7) Reconfigure Your mobile Setting if your Active sync enabled.
8) Check if any saved or scheduled task is configured for user account

Microsoft Kwoledge Bytes Link for Cache profile Removal Steps:

https://social.technet.microsoft.com/Forums/windows/en-US/ced8eab6-87e2-4d20-9d18-7aaf5e9713a3/windows-7-clear-cached-credentials"

 

Find the source of Account Lockouts in Active Directory

How to: Find the source of Account Lockouts in Active Directory

It is a very common problem in Active Directory when Users change their password in a domain environment, they might get locked out repeatedly and it can be a frustrating process to identify the source of the lockout.

Try the following steps to track the locked out user and also find the source of AD account lockouts. This procedure assume that you know the username which is locked out.

I recommend doing this procedure on ALL your Domain Controllers, not only your PDC Server, just to be sure you didn’t miss a lockout event.

  • You need to create a filter on the security log on your DCs. We will use a very handy XML query for that. These specific events are good for a 2008 R2 Domain Controller. You can easily change the event numbers for other Windows server editions.
  • To start, Right click security log and select ‘Filter current log’

Filter security log

  • Select the XML tab and tick the ‘Edit query manually‘ radio button.
  • Copy the following query to the XML window. You need to change the UserName and Domain\UserName  values respectively for your specific domain and user.
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">
            *[System[(EventID=4771 or EventID=4770 or EventID=4625 or EventID=6274)]]
            and
            *[EventData[Data and (Data='UserName' or Data='Domain\UserName')]]
          </Select>
  </Query>
</QueryList>

Filter locked user XML

 

  • Click OK to confirm the filter.
  • Now inside the events that were discovered in the security log, refer to the client address and client port to continue your investigation on the source of the lockout. in the below example you can see the source of lockout in the client address and client port lines.

event id 4771

Disconnect the user from the computers he is still trying to establish connections from.

You will receive all relevant events for the lockout for the specified user.

Power off the virtual machine in an ESXi host

Unable to power off the virtual machine in an ESXi host

Source: https://kb.vmware.com/s/article/1014165

Using the ESXi command-line utility vim-cmd to power off the virtual machine

  1. SSH into your ESXi server
  2. Get a list of all registered virtual machines, identified by their VMID, Display Name, and path to the .vmx configuration file by running this command: vim-cmd vmsvc/getallvms
    vim-cmd vmsvc/getallvms

  3. Get the current state of a virtual machine by running this command:
    vim-cmd vmsvc/power.getstate VMID

  4. Shutdown the virtual machine using the VMID found in Step 2 and run this command:
    vim-cmd vmsvc/power.shutdown VMID

  5. If the virtual machine fails to shut down, run this command:
    vim-cmd vmsvc/power.off VMID

Using the ESXi esxcli command to power off a virtual machine

The esxcli command can be used locally or remotely to power off a virtual machine running on ESXi 5.x or later.

  1. Open a console session where the esxcli tool is available, Isimply SSH to your ESXi machine.
  2. Get a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file by running this command:
    esxcli vm process list
  3. Power off the virtual machine from the list by running this command:
    esxcli vm process kill --type= [soft,hard,force] --world-id= WorldNumber

    Notes:

    • Three power-off methods are available. Soft is the most graceful, hard performs an immediate shutdown, and force should be used as a last resort.
    • alternate power off command syntax is: esxcli vm process kill -t [ soft,hard,force] -w WorldNumber
  4. Repeat Step 2 and validate that the virtual machine is no longer running.

 

 

 

 

How to run python script on notepad++

How to  Configure Notepad++ to run a python script via python IDLE

If you are learning python and want to use notepad++ as a free as well as simple and easy to use editor, follow these simple steps:

Install python (2.7.x)

First thing: Download the python 2.7.x (current is 2.7.13) windows installer from http://www.python.org/download/ using the default settings. It should install python in the folder: C:\Python27. You can use a different version of python, just substitute out the version number wherever you see 27. Continue reading How to run python script on notepad++

0x8007052e error in task scheduler

0x8007052e error in task scheduler

Symptom: You get 0x8007052e error when trying to run scheduled task from task scheduler.

There can be several causes for this including authentication problem like bad password.

But I did not easily find documented online records for this error being caused by a group policy, so I think this post might help you – system admins.

Continue reading 0x8007052e error in task scheduler

Installing SCOM 2012 agent on a workgroup or DMZ machine using Certificate

How to Install SCOM Agent on an Un-trusted machine

In order for SCOM to communicate with an un-trusted machine like in a WorkGroup / DMZ / different forest, you will have to import a certificate so that SCOM will trust the foreign machine and will be able to communicate with it. The most common example is a SCOM Gateway.
This topic is a bit complicated but if you use a guide like this you should be OK.

I added the files that you will need as well so you dont have to copy-paste it. Additional files: REQconfig.inf certreq

First thing you will need is an inf file that contains the request.

Continue reading Installing SCOM 2012 agent on a workgroup or DMZ machine using Certificate

Memory leak

Memory leak – when the Available MegaBytes (memory\% available Mbytes) for the system has exceeded the threshold, system performance may be significantly diminish, this results in low OS and applications performance. End users will usually complain about slow computer performance and you probably get a help-desk call like: ‘My computer is running slow’, or server is running slow.

Memory leaks can be caused by:

  • Too many applications running simultaneously on the computer.
  • An application may be leaking memory over time.

To view the history for the memory\% available Mbytes, start memory available Mbytes in performance monitor or event task manager\performance.

Continue reading Memory leak

Enable Remote Desktop remotely by using remote registry

Hi SysAdmins

I bet the following scenario happened to you:

You install a server, configure it, install the required programs, set its IP address etc..

After half a day of work (since you didn’t create an image) you send the server to its remote location.

When the server arrives to its site and the local technician plugs it in,

you discover that you forgot a small but very important V: Allow remote connection to this computer.

Continue reading Enable Remote Desktop remotely by using remote registry

Workstation Upgrade Consideration Guide

Hi SysAdmin

This guide will help you decide if adding more RAM, or upgrade the CPU will solve slow performance problems.

You can find out if memory or CPU upgrade is needed by configuring Performance Monitor to track memory and CPU usage.

You can then interpret the results and decide whether upgrade will improve the performance.

Use this guide before adding more RAM or upgrading CPU to a system with slow performance.

Continue reading Workstation Upgrade Consideration Guide