Skip to content

Commit

Permalink
Merge pull request #263 from P6g9YHK6/main
Browse files Browse the repository at this point in the history
Pumping more water into the dam
  • Loading branch information
silversword411 authored Dec 12, 2024
2 parents 7456fc2 + c7ca465 commit e860053
Show file tree
Hide file tree
Showing 40 changed files with 3,437 additions and 7 deletions.
74 changes: 74 additions & 0 deletions scripts_staging/Build/Create generic admin account.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<#
.SYNOPSIS
This script checks if an admin user exists, and if so, changes the password and ensures the user is added to the Administrators group.
.DESCRIPTION
The script retrieves the admin username from the environment variable `adminusername` and generates a passphrase.
It checks if the user exists on the system, then either updates the password for an existing user or creates the user if they do not exist.
It also ensures the user is added to both the 'Administrators' and 'Administrateurs' local groups and disables the password expiration.
.PARAMETER adminusername
The environment variable `adminusername` should be set with the desired username for the admin account.
.EXAMPLE
adminusername=adminUser
.NOTES
Author: SAN
Date: 01.01.24
Dependencies:
GeneratedPassphrase snippet
#public
.CHANGELOG
#>


{{GeneratedPassphrase}}

# Get admin username and password
$adminUsername = $env:adminusername
$adminPassword = $GeneratedPassphrase

# Check if the admin username is provided
if (-not $adminUsername) {
Write-Output "adminusername environment variable is not set. Exiting script."
exit 1
}

# Check if the user already exists
$existingUser = & net user $adminUsername 2>&1
if ($LASTEXITCODE -eq 0) {
# User already exists
Write-Output "The user '$adminUsername' already exists."
try {
# Change password
& net user $adminUsername $adminPassword
& wmic UserAccount where "Name='$adminUsername'" set PasswordExpires=False
& net localgroup Administrators $adminUsername /add
& net localgroup Administrateurs $adminUsername /add
Write-Output "The password for user '$adminUsername' has been changed."
}
catch {
Write-Output "Failed to change the password for user '$adminUsername'."
}
}
else {
# User doesn't exist
Write-Output "The user '$adminUsername' does not exist."
try {
# Create user
& net user $adminUsername $adminPassword /add /Y
Write-Output "The user '$adminUsername' has been created with the password '$adminPassword'."
& net localgroup Administrators $adminUsername /add
& net localgroup Administrateurs $adminUsername /add
Write-Output "The user '$adminUsername' has been added to the Administrators group."
& wmic UserAccount where "Name='$adminUsername'" set PasswordExpires=False
}
catch {
Write-Output "Failed to create the user '$adminUsername'."
}
}
126 changes: 126 additions & 0 deletions scripts_staging/Checks/Active Directory Health.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
<#
.SYNOPSIS
This script performs Active Directory (AD) diagnostics and compares Group Policy Object (GPO) version numbers between Sysvol and Active Directory.
.DESCRIPTION
The script performs a series of Active Directory tests using DCDIAG, checks for discrepancies in GPO versions between Sysvol and AD, and outputs the results.
It also checks if the Active Directory Domain Services (AD-DS) feature is installed on the system before performing these tests.
If any test fails, the exit code is incremented. The script provides detailed output for each test and comparison, indicating success or failure.
.NOTES
Author: SAN
Date: 01.01.24
#public
.CHANGELOG
#>

# Initialize exit code
$exitCode = 0

# Function to perform Active Directory tests
function CheckAD {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[string[]]$Tests
)

process {
$results = @{}

foreach ($test in $Tests) {
$output = dcdiag /test:$test

if ($output -notmatch "chou") {
$results[$test] = "OK"
} else {
$results[$test] = "Failed!"
$global:exitCode++
}

# Output individual test result
Write-Host "DCDIAG Test: $test Result: $($results[$test])"
}

$results
}
}

# Function to compare GPO version numbers

function Compare-GPOVersions {
[CmdletBinding()]
param ()

process {
Import-Module GroupPolicy

Get-GPO -All | ForEach-Object {
# Retrieve GPO information (GUID and Name)
$GPOId = $_.Id
$GPOName = $_.DisplayName

# Version GPO User
$NumUserSysvol = (Get-Gpo -Guid $GPOId).User.SysvolVersion
$NumUserAD = (Get-Gpo -Guid $GPOId).User.DSVersion

# Version GPO Machine
$NumComputerSysvol = (Get-Gpo -Guid $GPOId).Computer.SysvolVersion
$NumComputerAD = (Get-Gpo -Guid $GPOId).Computer.DSVersion

# USER - Compare version numbers
if ($NumUserSysvol -ne $NumUserAD) {
Write-Host "$GPOName ($GPOId) : USER Versions différentes (Sysvol : $NumUserSysvol | AD : $NumUserAD)" -ForegroundColor Red
$global:exitCode++
} else {
Write-Host "$GPOName : USER Versions identiques" -ForegroundColor Green
}

# COMPUTER - Compare version numbers
if ($NumComputerSysvol -ne $NumComputerAD) {
Write-Host "$GPOName ($GPOId) : COMPUTER Versions différentes (Sysvol : $NumComputerSysvol | AD : $NumComputerAD)" -ForegroundColor Red
$global:exitCode++
} else {
Write-Host "$GPOName : COMPUTER Versions identiques" -ForegroundColor Green
}
}
Write-Host "GPO USER/COMPUTER Version OK" -ForegroundColor Green
}
}

# Check if Active Directory Domain Services feature is installed
try {
$adFeature = Get-WindowsFeature -Name AD-Domain-Services -ErrorAction Stop

if ($adFeature.InstallState -eq "Installed") {
# Specify your AD tests
$tests = ("Advertising", "FrsSysVol", "MachineAccount", "Replications", "RidManager", "Services", "FsmoCheck", "SysVolCheck")
# Call the function with the AD tests
Write-Host "DCDIAG"
$testResults = CheckAD -Tests $tests

$failedTests = $testResults.GetEnumerator() | Where-Object { $_.Value -eq "Failed!" }

if ($failedTests) {
Write-Error "Some Active Directory tests failed."
$failedTests | ForEach-Object { Write-Error "$($_.Key) test failed." }
$global:exitCode += $failedTests.Count
} else {
Write-Host "All Active Directory tests passed successfully."
}
Write-Host ""
Write-Host "GPO Versions checks"
# Call the function to compare GPO versions
Compare-GPOVersions
} else {
Write-Host "Active Directory Domain Services feature is not installed or not in the 'Installed' state."
exit
}
} catch {
Write-Error "Failed to retrieve information about Active Directory Domain Services feature: $_"
$global:exitCode++
}

exit $exitCode
6 changes: 3 additions & 3 deletions scripts_staging/Checks/Boot mode.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
#public
.CHANGELOG
12.12.24 SAN Changed outputs
#>

Expand All @@ -21,9 +21,9 @@ $regPath = "HKLM:\SYSTEM\CurrentControlSet\Control\SafeBoot\Option"
$safeModeKeyExists = Test-Path $regPath

if ($safeModeKeyExists) {
Write-Host "System is booted in Safe Mode."
Write-Host "KO: System is booted in Safe Mode."
exit 1
} else {
Write-Host "System is not booted in Safe Mode."
Write-Host "OK: System is not booted in Safe Mode."
exit 0
}
133 changes: 133 additions & 0 deletions scripts_staging/Checks/DFS replication.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<#
.SYNOPSIS
Monitors DFS Replication backlog and generates status based on the file count in the backlog for specified replication groups.
.DESCRIPTION
This script checks the DFS Replication backlog for specified replication groups using WMI queries and the 'dfsrdiag' command.
It generates success, warning, or error statuses based on the backlog file count, helping to monitor replication health.
.PARAMETER ReplicationGroupList
An array of DFS Replication Group names to monitor. If not specified, all groups will be checked.
This can be specified through the variable `ReplicationGroupList`.
.EXAMPLE
ReplicationGroupList = @("Group1", "Group2")
This will check the backlog for "Group1" and "Group2" replication groups.
.NOTES
Author: matty-uk
Date: ????
Usefull links:
https://exchange.nagios.org/directory/Addons/Monitoring-Agents/DFSR-Replication-and-BackLog/details
#public
.CHANGELOG
01.01.24 SAN Re-implementation for rmm
12.12.24 SAN code cleanup
.TODO
Add additional options for backlog threshold customization.
move list to env
#>



# Define parameter for specifying replication groups (default is an empty array)
Param (
[String[]]$ReplicationGroupList = @("") # Default is no specific group
)

# Retrieve all DFS Replication Group configurations via WMI
$ReplicationGroups = Get-WmiObject -Namespace "root\MicrosoftDFS" -Query "SELECT * FROM DfsrReplicationGroupConfig"

# Filter replication groups if specific group names are provided
if ($ReplicationGroupList) {
$FilteredReplicationGroups = @()
foreach ($ReplicationGroup in $ReplicationGroupList) {
$FilteredReplicationGroups += $ReplicationGroups | Where-Object { $_.ReplicationGroupName -eq $ReplicationGroup }
}

# Exit with UNKNOWN status if no groups match
if ($FilteredReplicationGroups.Count -eq 0) {
Write-Host "UNKNOWN: None of the specified group names were found."
exit 3
} else {
$ReplicationGroups = $FilteredReplicationGroups
}
}

# Initialize counters for success, warning, and error
$SuccessCount = 0
$WarningCount = 0
$ErrorCount = 0

# Initialize an array to store output messages
$OutputMessages = @()

# Iterate through each DFS Replication Group
foreach ($ReplicationGroup in $ReplicationGroups) {
# Query for DFS Replicated Folder configurations for the current replication group
$ReplicatedFoldersQuery = "SELECT * FROM DfsrReplicatedFolderConfig WHERE ReplicationGroupGUID='" + $ReplicationGroup.ReplicationGroupGUID + "'"
$ReplicatedFolders = Get-WmiObject -Namespace "root\MicrosoftDFS" -Query $ReplicatedFoldersQuery

# Query for DFS Replication Connection configurations for the current replication group
$ReplicationConnectionsQuery = "SELECT * FROM DfsrConnectionConfig WHERE ReplicationGroupGUID='" + $ReplicationGroup.ReplicationGroupGUID + "'"
$ReplicationConnections = Get-WmiObject -Namespace "root\MicrosoftDFS" -Query $ReplicationConnectionsQuery

# Iterate through each DFS Replication Connection for the current replication group
foreach ($ReplicationConnection in $ReplicationConnections) {
$ConnectionName = $ReplicationConnection.PartnerName

# Check if the connection is enabled
if ($ReplicationConnection.Enabled -eq $True) {
# Iterate through each DFS Replicated Folder for the current connection
foreach ($ReplicatedFolder in $ReplicatedFolders) {
$ReplicationGroupName = $ReplicationGroup.ReplicationGroupName
$ReplicatedFolderName = $ReplicatedFolder.ReplicatedFolderName

# Execute the 'dfsrdiag' command to get backlog information
$BacklogCommand = "dfsrdiag Backlog /RGName:'$ReplicationGroupName' /RFName:'$ReplicatedFolderName' /SendingMember:$ConnectionName /ReceivingMember:$env:ComputerName"
$BacklogOutput = Invoke-Expression -Command $BacklogCommand

$BacklogFileCount = 0
# Parse the 'dfsrdiag' output to retrieve the backlog file count
foreach ($Item in $BacklogOutput) {
if ($Item -ilike "*Backlog File count*") {
$BacklogFileCount = [int]$Item.Split(":")[1].Trim()
}
}

# Generate status messages based on backlog file count and update counters
if ($BacklogFileCount -eq 0) {
$OutputMessages += "OK: $BacklogFileCount files in backlog for $ConnectionName->$env:ComputerName in $ReplicationGroupName"
$SuccessCount++
} elseif ($BacklogFileCount -lt 10) {
$OutputMessages += "WARNING: $BacklogFileCount files in backlog for $ConnectionName->$env:ComputerName in $ReplicationGroupName"
$WarningCount++
} else {
$OutputMessages += "CRITICAL: $BacklogFileCount files in backlog for $ConnectionName->$env:ComputerName in $ReplicationGroupName"
$ErrorCount++
}
}
}
}
}

# Generate the final status based on the success, warning, and error counters
if ($ErrorCount -gt 0) {
Write-Host "CRITICAL: $ErrorCount errors, $WarningCount warnings, and $SuccessCount successful replications."
Write-Host "$OutputMessages"
$host.SetShouldExit(2)
exit 2
} elseif ($WarningCount -gt 0) {
Write-Host "WARNING: $WarningCount warnings, and $SuccessCount successful replications."
Write-Host "$OutputMessages"
$host.SetShouldExit(1)
exit 1
} else {
Write-Host "OK: $SuccessCount successful replications."
Write-Host "$OutputMessages"
$host.SetShouldExit(0)
exit 0
}
Loading

0 comments on commit e860053

Please sign in to comment.