2
0

Change default server to localhost

This commit is contained in:
2025-11-03 07:33:37 +00:00
parent b0fdf75a53
commit 96f2085a20

View File

@@ -1,15 +1,15 @@
<# <#
.SYNOPSIS .SYNOPSIS
Installs, configures, and secures the SNMP Service and components on a remote Windows Server. Installs, configures, and secures the SNMP Service and components on a remote or local Windows Server.
It includes optional parameters for setting Agent Contact and Location details.
.DESCRIPTION .DESCRIPTION
This script is idempotent. It installs the SNMP features, uses the RFC1156Agent key to set sysServices, sysContact, and sysLocation, This script is idempotent. It installs the SNMP features, sets Agent details, configures the Community String,
configures the Community String (Read Only), checks if the Allowed IP is already present before adding it to the Permitted Managers, checks if the Allowed IP is already present before adding it, creates missing registry keys only if needed,
creates missing registry keys only if needed, and opens UDP 161 in the Windows Firewall. opens UDP 161 in the Windows Firewall, and correctly executes commands locally if the target is the local machine
(bypassing Invoke-Command for local execution).
.PARAMETER ComputerName .PARAMETER ComputerName
The name of the remote computer (Windows Server) where SNMP will be installed. The name of the remote computer (Windows Server) where SNMP will be installed. Defaults to the local machine if not specified.
.PARAMETER CommunityString .PARAMETER CommunityString
The custom community string to be configured for the SNMP Service. The custom community string to be configured for the SNMP Service.
@@ -25,14 +25,16 @@ Optional. The contact person or email address for the SNMP agent (written to sys
Optional. The physical location of the SNMP agent (written to sysLocation). Optional. The physical location of the SNMP agent (written to sysLocation).
.EXAMPLE .EXAMPLE
.\Install-Configure-SNMP.ps1 -ComputerName "Server01" -CommunityString "MySecureString" -AllowedIPOrHost "192.168.1.10" -AgentContact "IT Operations" -AgentLocation "Server Room A" # Run on the local machine (commands execute directly, no Invoke-Command)
.\Install-Configure-SNMP.ps1 -CommunityString "MySecureString" -AllowedIPOrHost "192.168.1.10"
.EXAMPLE .EXAMPLE
.\Install-Configure-SNMP.ps1 -ComputerName "TestServer" -CommunityString "PublicAccess" -AllowedIPOrHost "0.0.0.0" # Run on a remote machine (commands execute via Invoke-Command)
.\Install-Configure-SNMP.ps1 -ComputerName "Server01" -CommunityString "MySecureString" -AllowedIPOrHost "192.168.1.10" -AgentContact "IT Operations"
#> #>
param( param(
[Parameter(Mandatory=$true)] [Parameter(Mandatory=$false)]
[string]$ComputerName, [string]$ComputerName = $env:COMPUTERNAME,
[Parameter(Mandatory=$true)] [Parameter(Mandatory=$true)]
[string]$CommunityString, [string]$CommunityString,
@@ -53,19 +55,45 @@ $FirewallRuleName = "Allow-SNMP-Inbound-UDP161"
$SNMPPort = 161 $SNMPPort = 161
$AgentServicesName = "sysServices" $AgentServicesName = "sysServices"
$AgentServicesValue = 79 $AgentServicesValue = 79
$IsLocal = ($ComputerName -ceq $env:COMPUTERNAME) # Check if target is the local machine (case-exact)
Write-Host "--- Starting SNMP Service installation, configuration, and firewall setup on $($ComputerName) ---" Write-Host "--- Starting SNMP Service installation, configuration, and firewall setup on $($ComputerName) ---"
if ($IsLocal) {
Write-Host "NOTE: Running in LOCAL execution mode (bypassing Invoke-Command). 🖥️"
} else {
Write-Host "NOTE: Running in REMOTE execution mode (using Invoke-Command). 🌐"
}
Write-Host "--------------------------------------------------------------------------------"
# --- Function to handle execution (Local or Remote) ---
function Execute-ScriptBlock {
param(
[ScriptBlock]$ScriptBlock,
[Array]$ArgumentList
)
if ($IsLocal) {
# Run locally by invoking the script block directly
& $ScriptBlock @ArgumentList
} else {
# Run remotely via Invoke-Command
Invoke-Command -ComputerName $ComputerName -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList -ErrorAction Stop
}
}
# -----------------------------------------------------
try { try {
# 1. Install SNMP Service and WMI Provider (including RSAT-SNMP) remotely # 1. Install SNMP Service and WMI Provider (including RSAT-SNMP)
Write-Host "1. Installing $($SNMPFeatures -join ', ') on $($ComputerName)..." Write-Host "1. Installing $($SNMPFeatures -join ', ') on $($ComputerName)..."
Invoke-Command -ComputerName $ComputerName -ScriptBlock { $InstallFeaturesBlock = {
param($Features) param($Features)
# Install the features if not already present
$InstalledFeatures = Get-WindowsFeature $Features | Where-Object { $_.Installed -eq $true } $InstalledFeatures = Get-WindowsFeature $Features | Where-Object { $_.Installed -eq $true }
if ($InstalledFeatures.Count -ne $Features.Count) { if ($InstalledFeatures.Count -ne $Features.Count) {
Write-Host "Installing features..." Write-Host "Installing features..."
# Using -IncludeAllSubFeature to ensure all dependencies are met
$InstallationResult = Install-WindowsFeature -Name $Features -IncludeAllSubFeature -ErrorAction Stop $InstallationResult = Install-WindowsFeature -Name $Features -IncludeAllSubFeature -ErrorAction Stop
if (-not $InstallationResult.Success) { if (-not $InstallationResult.Success) {
throw "Feature installation failed. Details: $($InstallationResult | Out-String)" throw "Feature installation failed. Details: $($InstallationResult | Out-String)"
@@ -73,12 +101,13 @@ try {
} else { } else {
Write-Host "SNMP features are already installed." Write-Host "SNMP features are already installed."
} }
} -ArgumentList $SNMPFeatures -ErrorAction Stop }
Execute-ScriptBlock -ScriptBlock $InstallFeaturesBlock -ArgumentList @($SNMPFeatures)
# 2. Configure SNMP Service remotely (Contact, Location, Community String, Allowed IPs, and Agent Services) # 2. Configure SNMP Service (Contact, Location, Community String, Allowed IPs, and Agent Services)
Write-Host "2. Configuring SNMP Service parameters on $($ComputerName)..." Write-Host "2. Configuring SNMP Service parameters on $($ComputerName)..."
Invoke-Command -ComputerName $ComputerName -ScriptBlock { $ConfigureSNMPBlock = {
param($Community, $IPOrHost, $ServicesName, $ServicesValue, $Contact, $Location) param($Community, $IPOrHost, $ServicesName, $ServicesValue, $Contact, $Location)
# Define Registry paths # Define Registry paths
@@ -93,6 +122,7 @@ try {
# Check and create the parent 'Parameters' key if it's missing (needed for subsequent checks) # Check and create the parent 'Parameters' key if it's missing (needed for subsequent checks)
if (-not (Test-Path $SNMPRegBase)) { if (-not (Test-Path $SNMPRegBase)) {
Write-Host " -> Creating base Parameters key: $SNMPRegBase" Write-Host " -> Creating base Parameters key: $SNMPRegBase"
# Using -Force here is necessary to ensure it's created if 'SNMP' exists but 'Parameters' doesn't.
New-Item -Path $SNMPRegBase -Type Directory -Force -ErrorAction Stop | Out-Null New-Item -Path $SNMPRegBase -Type Directory -Force -ErrorAction Stop | Out-Null
} }
@@ -113,7 +143,6 @@ try {
# --- Configure Agent Contact (sysContact) --- # --- Configure Agent Contact (sysContact) ---
if (-not [string]::IsNullOrEmpty($Contact)) { if (-not [string]::IsNullOrEmpty($Contact)) {
Write-Host " -> Setting Agent Contact (sysContact) to '$Contact'." Write-Host " -> Setting Agent Contact (sysContact) to '$Contact'."
# Use Type STRING (RegSZ) for text fields
Set-ItemProperty -Path $RFC1156AgentRegKey -Name "sysContact" -Value $Contact -Type String -Force -ErrorAction Stop Set-ItemProperty -Path $RFC1156AgentRegKey -Name "sysContact" -Value $Contact -Type String -Force -ErrorAction Stop
} else { } else {
Write-Host " -> Agent Contact parameter was empty, skipping sysContact configuration." Write-Host " -> Agent Contact parameter was empty, skipping sysContact configuration."
@@ -122,7 +151,6 @@ try {
# --- Configure Agent Location (sysLocation) --- # --- Configure Agent Location (sysLocation) ---
if (-not [string]::IsNullOrEmpty($Location)) { if (-not [string]::IsNullOrEmpty($Location)) {
Write-Host " -> Setting Agent Location (sysLocation) to '$Location'." Write-Host " -> Setting Agent Location (sysLocation) to '$Location'."
# Use Type STRING (RegSZ) for text fields
Set-ItemProperty -Path $RFC1156AgentRegKey -Name "sysLocation" -Value $Location -Type String -Force -ErrorAction Stop Set-ItemProperty -Path $RFC1156AgentRegKey -Name "sysLocation" -Value $Location -Type String -Force -ErrorAction Stop
} else { } else {
Write-Host " -> Agent Location parameter was empty, skipping sysLocation configuration." Write-Host " -> Agent Location parameter was empty, skipping sysLocation configuration."
@@ -154,12 +182,13 @@ try {
Set-ItemProperty -Path $PermittedManagersRegKey -Name $Index -Value $IPOrHost -Type STRING -Force -ErrorAction Stop Set-ItemProperty -Path $PermittedManagersRegKey -Name $Index -Value $IPOrHost -Type STRING -Force -ErrorAction Stop
} }
} -ArgumentList $CommunityString, $AllowedIPOrHost, $AgentServicesName, $AgentServicesValue, $AgentContact, $AgentLocation -ErrorAction Stop }
Execute-ScriptBlock -ScriptBlock $ConfigureSNMPBlock -ArgumentList @($CommunityString, $AllowedIPOrHost, $AgentServicesName, $AgentServicesValue, $AgentContact, $AgentLocation)
# 3. Configure Windows Firewall Rule (Idempotent: removes and re-creates) # 3. Configure Windows Firewall Rule (Idempotent: removes and re-creates)
Write-Host "3. Configuring Windows Firewall to allow UDP port $($SNMPPort) from $($AllowedIPOrHost) on $($ComputerName)..." Write-Host "3. Configuring Windows Firewall to allow UDP port $($SNMPPort) from $($AllowedIPOrHost) on $($ComputerName)..."
Invoke-Command -ComputerName $ComputerName -ScriptBlock { $ConfigureFirewallBlock = {
param($RuleName, $Port, $IPOrHost) param($RuleName, $Port, $IPOrHost)
# Remove existing rule if it exists (for clean updates) # Remove existing rule if it exists (for clean updates)
@@ -179,14 +208,16 @@ try {
-Profile Any ` -Profile Any `
-ErrorAction Stop -ErrorAction Stop
} -ArgumentList $FirewallRuleName, $SNMPPort, $AllowedIPOrHost -ErrorAction Stop }
Execute-ScriptBlock -ScriptBlock $ConfigureFirewallBlock -ArgumentList @($FirewallRuleName, $SNMPPort, $AllowedIPOrHost)
# 4. Restart SNMP Service # 4. Restart SNMP Service
Write-Host "4. Restarting SNMP Service on $($ComputerName) to apply all changes (Configuration & Firewall)." Write-Host "4. Restarting SNMP Service on $($ComputerName) to apply all changes (Configuration & Firewall)."
Invoke-Command -ComputerName $ComputerName -ScriptBlock { $RestartServiceBlock = {
Restart-Service -Name "SNMP" -ErrorAction Stop Restart-Service -Name "SNMP" -ErrorAction Stop
} -ErrorAction Stop }
Execute-ScriptBlock -ScriptBlock $RestartServiceBlock
Write-Host "--- SNMP installation, configuration, and firewall setup on $($ComputerName) is complete! ✅ ---" Write-Host "--- SNMP installation, configuration, and firewall setup on $($ComputerName) is complete! ✅ ---"