Las direcciones IPv4 pueden estar definidas en el propio script, o en un archivo de texto local.
En la cabecera del script, se puede asignar el valor apropiado para especificar la ruta de un archivo que contenga direcciones IPv4:
Código:
$ipv4ListFile = "$PSScriptRoot\Ipv4.txt"
Ejemplo del contenido del archivo:
Código:
172.64.149.23
192.229.221.95
20.190.177.85
20.73.194.208
O directamente también se pueden establecer las IPv4 a bloquear, en el siguiente array:
Código:
$ipArray = @()
Block IP addresses.ps1
Código
# Script Version 1.3 <# =========================================================================================== | | | User Settings | | | =========================================================================================== #> # Path to a plain text file containing IP addresses. # Note: The file must contain a single IP address per line. [string] ` $ipListFile = "$PSScriptRoot\Ipv4.txt" # An Array with additional IP addresses to block. [string[]] ` $ipArray = @() <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +=======================================+" Write-Host " | |" Write-Host " | This script will add firewall rules |" Write-Host " | to block network traffic for the IP |" Write-Host " | addresses specified in the input file |" Write-Host " | and/or defined in this script file. |" Write-Host " | |" Write-Host " +=======================================+" Write-Host "" Write-Host " Input File Path: $ipListFile" -ForegroundColor DarkGray Write-Host "" Write-Host " IP addresses hardcoded in this script: $($ipArray.Count)" -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' key to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} } function Show-GoodbyeScreen { Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") } function Add-FirewallRules { param ( [string]$ipListFile, [string[]]$ipArray ) Write-Host "Compiling internal C# code..." # Natural Sorting C# Snippet Add-Type -TypeDefinition ' using System; using System.Collections.Generic; using System.Runtime.InteropServices; public static class NativeMethods { [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] public static extern int StrCmpLogicalW(string first, string second); } public class NaturalStringComparer : IComparer<string> { public int Compare(string first, string second) { return NativeMethods.StrCmpLogicalW(first, second); } } ' Write-Host "Fetching computer's firewall rules..." $ruleGroupName = "$env:COMPUTERNAME IP Blocks" [CimInstance[]]$currentRules = Get-NetFirewallRule -Group $ruleGroupName -ErrorAction SilentlyContinue Write-Host "Building IP address collection..." $comparer = [NaturalStringComparer]::new() $sortedSet = [System.Collections.Generic.SortedSet[string]]::new($ipArray, $comparer) if (Test-Path $ipListFile) { Write-Host "Fetching IP addresses from input file..." $ipList = Get-Content -Path $ipListFile | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } foreach ($ip in $ipList) { $sortedSet.Add($ip) | Out-Null } } if ($sortedSet.Count -eq 0) { Write-Warning "There are no IP addresses to process." return } $totalItemCount = $sortedSet.Count $currentItemIndex = 0 Write-Host "Start processing IP address collection..." Write-Host "" foreach ($ip in $sortedSet) { $currentItemIndex +=1 Write-Host "[$currentItemIndex of $totalItemCount] IP address: $ip" $ruleNameInbound = "IP Block (Inbound) ($ip)" $currentRules | Where-Object { $_.DisplayName -eq $ruleNameInbound } -ErrorAction SilentlyContinue | Remove-NetFirewallRule Write-Host "Adding firewall rule to block inbound traffic..." -ForegroundColor DarkGray [CimInstance]$ruleInbound = New-NetFirewallRule ` -DisplayName "$ruleNameInbound" ` -Description "This rule disables incoming traffic for address: $ip" ` -Group "$ruleGroupName" ` -Direction "Inbound" ` -Action "Block" ` -RemoteAddress "$ip" ` -Profile "Any" ` -Enabled "True" ` -LocalAddress "Any" ` -InterfaceType "Any" $ruleNameOutbound = "IP Block (Outbound) ($ip)" $currentRules | Where-Object { $_.DisplayName -eq $ruleNameOutbound } -ErrorAction SilentlyContinue | Remove-NetFirewallRule Write-Host "Adding firewall rule to block outbound traffic..." -ForegroundColor DarkGray [CimInstance]$ruleOutbound = New-NetFirewallRule ` -DisplayName "$ruleNameOutbound" ` -Description "This rule disables outgoing traffic for address: $ip" ` -Group "$ruleGroupName" ` -Direction "Outbound" ` -Action "Block" ` -RemoteAddress "$ip" ` -Profile "Any" ` -Enabled "True" ` -LocalAddress "Any" ` -InterfaceType "Any" Write-Host "" } } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Block IP addresses - by Elektro" [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Add-FirewallRules -ipListFile $ipListFile -ipArray $ipArray Show-GoodbyeScreen Exit(0)
Notas:
- Probado en Windows 10 (PowerShell 5.1.19041.1682). Debería funcionar igual en Windows 11.
EDITADO: Script actualizado a la versión 1.1. Al final he decidido utilizar el cmdlet New-NetFirewallRule a pesar de los inconvenientes, por que entiendo que así será más compatible y útil para más gente.
EDITADO: Script actualizado a la versión 1.2. Se ha mejorado bastante la velocidad de ejecución del código, optimizando la metodología de obtención de las reglas de firewall del equipo.
EDITADO: Script actualizado a la versión 1.3. Últimos ajustes y micro-optimizaciones aplicados ().