So überwachen Sie die letzte Anmeldung eines Benutzers mit PowerShell

Eine der wichtigsten Aufgaben des modernen IT-Managements ist die Überwachung von Benutzerkonten, insbesondere die Identifizierung inaktiver Konten. Bei diesem Unterfangen geht es um mehr als nur um die Haushaltsführung. Sie steht in direktem Zusammenhang mit Sicherheit, Einhaltung von Vorschriften und effizienter Ressourcenverwaltung. Heute befassen wir uns mit einem PowerShell-Skript, das die Überwachung der letzten Anmeldung eines Benutzersermöglicht

Hintergrund

Das bereitgestellte Skript dient dazu, Benutzerkonten auf der Grundlage ihrer letzten Anmeldezeit zu identifizieren und einen Bericht darüber zu erstellen, insbesondere solche, die über einen bestimmten Zeitraum nicht benutzt wurden. Für IT-Experten und Managed Service Provider (MSPs) ist es von entscheidender Bedeutung, dass ungenutzte Konten identifiziert und verwaltet werden. Ruhende Konten stellen ein Sicherheitsrisiko dar und sind oft ein leichtes Ziel für Cyberkriminelle. Für Unternehmen, die Compliance-Vorschriften einhalten müssen, kann es außerdem erforderlich sein, die Benutzeraktivitäten zu verfolgen und ungenutzte Konten zu deaktivieren.

Das Skript

#Requires -Version 5.1

<#
.SYNOPSIS
    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 90 days or a custom amount of days.
.DESCRIPTION
    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 90 days or a custom amount of days.
.EXAMPLE
    No parameters needed.
    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 90 days.
.EXAMPLE
    -IncludeDisabled
    Returns exit code of 1 if any Enabled or Disabled accounts that haven't been logged in over 90 days.
.EXAMPLE
    -Days 60
    Returns exit code of 1 if any Enabled accounts that haven't been logged in over 60 days.
.EXAMPLE
    -Days 60 -IncludeDisabled
    Returns exit code of 1 if any Enabled or Disabled accounts that haven't been logged in over 60 days.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2012
    Exit code 1: Found users that haven't logged in over X days and are enabled.
    Exit code 2: Calling "net.exe user" or "Get-LocalUser" failed.
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ManageUsers
#>

[CmdletBinding()]
param (
    [Parameter()]
    [int]
    $Days = 90,
    [Parameter()]
    [switch]
    $IncludeDisabled
)

begin {}
process {
    if ($Days -lt 0) {
        # Change negative days to the expected positive days
        $Days = 0 - $Days
    }
    $Accounts = if ($(Get-Command "Get-LocalUser").Name -like "Get-LocalUser") {
        try {
            Get-LocalUser | Select-Object Name, Enabled, SID, LastLogon
        }
        catch {
            exit 2
        }
    }
    else {
        # Get users from net.exe user
        $Data = $(net.exe user) | Select-Object -Skip 4
        # Check if the command ran the way we wanted and the exit code is 0
        if ($($Data | Select-Object -Last 2 | Select-Object -First 1) -like "*The command completed successfully.*" -and $LASTEXITCODE -eq 0) {
            # Process the output and get only the users
            $Users = $Data[0..($Data.Count - 3)] -split 's+' | Where-Object { -not $([String]::IsNullOrEmpty($_)) }
            # Loop through each user
            $Users | ForEach-Object {
                # Get the Account active property look for a Yes
                $Enabled = $(net.exe user $_) | Where-Object {
                    $_ -like "Account active*" -and
                    $($_ -split 's+' | Select-Object -Last 1) -like "Yes"
                }
                # Get the Last logon property
                $LastLogon = $(
                    $(
                        $(net.exe user $_) | Where-Object {
                            $_ -like "Last logon*"
                        }
                    ) -split 's+' | Select-Object -Skip 2
                ) -join ' '
                # Get the Password last set property
                $PasswordLastSet = $(
                    $(
                        $(net.exe user $_) | Where-Object {
                            $_ -like "Password last set*"
                        }
                    ) -split 's+' | Select-Object -Skip 3
                ) -join ' '
                # Output Name and Enabled almost like how Get-LocalUser displays it's data
                [PSCustomObject]@{
                    Name      = $_
                    Enabled   = if ($Enabled -like "*Yes*") { $true }else { $false }
                    LastLogon = if ($LastLogon -like "*Never*") { [DateTime]::Parse($PasswordLastSet) } else { [DateTime]::Parse($LastLogon) }
                }
            }
        }
        else {
            exit 2
        }
    }
    $Output = $Accounts | Where-Object {
        if ($IncludeDisabled) {
            $_.LastLogon -lt $(Get-Date).AddDays(0 - $Days)
        }
        else {
            $_.Enabled -and $_.LastLogon -lt $(Get-Date).AddDays(0 - $Days)
        }
    }
    $Output | Out-String | Write-Host
    if ($null -ne $Output) {
        exit 1
    }
}
end {}

 

Zugriff auf über 300 Skripte im NinjaOne Dojo

Zugang erhalten

Detailansicht

Das Skript beginnt mit einer Standarddauer von 90 Tagen für die Prüfung auf Inaktivität. Anschließend wird entweder das Cmdlet „Get-LocalUser“ oder der Befehl „net.exe user“ verwendet, je nachdem, was verfügbar ist.

  • Wenn das Cmdlet „Get-LocalUser“ vorhanden ist, holt es die Details direkt ab.
  • Ist dies nicht der Fall, wird auf den Befehl „net.exe user“ zurückgegriffen. Dieser Befehl ruft die Daten ab und verarbeitet dann die Ausgabe, um die gewünschten Details herauszufiltern.

Die primäre Logik besteht darin, zu prüfen, ob das letzte Anmeldedatum jedes Benutzers älter ist als der festgelegte Schwellenwert. Wenn eine Übereinstimmung gefunden wird, wird sie angezeigt, und das Skript wird mit einem Code von 1 beendet. Ein Exit-Code von 2 wird für Ausnahmen beim Abrufen von Benutzerdaten verwendet.

Potenzielle Anwendungsfälle

Stellen Sie sich Jane vor, eine IT-Fachkraft in einem mittelständischen Unternehmen. Kürzlich hatte das Unternehmen mit einer kleineren Sicherheitsverletzung zu kämpfen. Nach dem Vorfall wurde Jane damit beauftragt, die Sicherheitsvorkehrungen zu verstärken. Einer der Vorschläge war, regelmäßig nach inaktiven Konten zu suchen und diese zu deaktivieren. Mit diesem Skript kann sie eine monatliche Routine einrichten, um eine Liste solcher Konten abzurufen und sicherzustellen, dass das Benutzerverzeichnis des Unternehmens aktiv und sicher bleibt.

Vergleiche

Während das Skript die PowerShell nutzt, könnte ein anderer Ansatz darin bestehen, das Active Directory (falls verfügbar) direkt nach Benutzerkontodetails abzufragen. Es können Tools wie ADManager Plus oder sogar das integrierte Active Directory Users and Computers (ADUC) verwendet werden. Unser Skript bietet jedoch eine leichtgewichtige, anpassbare und kostenlose Alternative.

FAQs

  • Was ist, wenn ich nach einer anderen Dauer der Inaktivität suchen möchte?
    Sie können den Parameter $Days anpassen.
  • Kann das Skript sowohl aktivierte als auch deaktivierte Konten erkennen?
    Ja, mit der Option -IncludeDisabled kann das Skript sowohl aktivierte als auch deaktivierte Konten abrufen.

Auswirkungen

Neben der Identifizierung ruhender Konten hat dieses Skript auch Auswirkungen auf die IT-Sicherheit. Inaktive Konten können leicht kompromittiert werden, so dass Unbefugte Zugang erhalten. Regelmäßige Überprüfungen der Inaktivität von Benutzern und entsprechende Maßnahmen können mögliche Verstöße verhindern.

Empfehlungen

  • Testen Sie das Skript immer in einer abgeschotteten Umgebung, bevor Sie es weitreichend implementieren.
  • Planen Sie die Ausführung dieses Skripts in regelmäßigen Abständen, um eine kontinuierliche Überwachung zu gewährleisten.
  • Nach Identifizierung von inaktiven Konten sollten entsprechende Maßnahmen ergriffen werden, wie beispielsweise das Deaktivieren des Kontos oder die Benachrichtigung des Benutzers oder seines Managers.

Abschließende Überlegungen

Während das Skript eine effiziente Lösung darstellt, kann die Integration von Tools wie NinjaOne die Möglichkeiten weiter verbessern, indem Aufgaben automatisiert werden und ein zentrales Dashboard für das Managementbereitgestellt wird. Tools wie NinjaOne sind darauf ausgelegt, solche Aufgaben effizient zu erledigen, so dass sich IT-Experten wie Jane auf strategischere Aufgaben konzentrieren können, indem sie Skripte wie das obige als Teil eines umfassenderen Toolkits nutzen.

Nächste Schritte

Der Aufbau eines effizienten und effektiven IT-Teams erfordert eine zentralisierte Lösung, die als vereintes Tool für die Bereitstellung von Dienstleistungen fungiert. NinjaOne ermöglicht es IT-Teams, all ihre Geräte zu überwachen, verwalten, sichern und zu unterstützen, unabhängig von ihrem Ort und komplexer Infrastruktur vor Ort.

Erfahren Sie mehr über NinjaOne Endpoint Management schauen Sie sich eine Live-Tour an oder starten Sie Ihre kostenlose Testversion der NinjaOne Plattform.

Kategorien:

Das könnte Sie auch interessieren

Demo ansehen×
×

Sehen Sie NinjaOne in Aktion!

Mit dem Absenden dieses Formulars akzeptiere ich die Datenschutzerklärung von NinjaOne.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).