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.1 <# =========================================================================================== | | | User Settings | | | =========================================================================================== #> # Note: The file must contain a single IP address per line. $ipListFile = "$PSScriptRoot\Ipv4.txt" # Additional IP addresses to block: $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, [System.Collections.ArrayList]$ipArray ) if (Test-Path $ipListFile) { Write-Host "Fetching IP addresses from input file..." -ForegroundColor DarkGray Write-Host "" $ipArray += Get-Content -Path $ipListFile | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } } # Natural Sorting C# Snippet Add-Type -TypeDefinition ' using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; namespace StringComparers { public static class NativeMethods { [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] public static extern int StrCmpLogicalW(string psz1, string psz2); public static System.Collections.ArrayList Sort(System.Collections.ArrayList foo) { foo.Sort(new NaturalSortComparer()); return foo; } } public class NaturalSortComparer : IComparer { public int Compare(object x, object y) { return NativeMethods.StrCmpLogicalW(x.ToString(), y.ToString()); } } }' # Sort items and remove duplicated items. $ipArray = $ipArray | Select-Object -Unique $naturalSortComparer = New-Object StringComparers.NaturalSortComparer $ipArray.Sort($naturalSortComparer) if ($ipArray.Count -eq 0) { Write-Warning "There are no IP addresses to process." return } $ruleGroupName = "$env:COMPUTERNAME IP Blocks" $currentItemIndex = 0 $totalItemCount = $ipArray.Count foreach ($ip in $ipArray) { $currentItemIndex +=1 Write-Host "[$currentItemIndex of $totalItemCount] IP address: $ip" $ruleNameInbound = "IP Block (Inbound) ($ip)" Write-Host "Adding firewall rule to block inbound traffic..." -ForegroundColor DarkGray Get-NetFirewallRule -DisplayName "$ruleNameInbound" -ErrorAction SilentlyContinue | Remove-NetFirewallRule [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)" Write-Host "Adding firewall rule to block outbound traffic..." -ForegroundColor DarkGray Get-NetFirewallRule -DisplayName "$ruleNameOutbound" -ErrorAction SilentlyContinue | Remove-NetFirewallRule [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. 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.