{"id":208619,"date":"2024-01-30T16:44:16","date_gmt":"2024-01-30T16:44:16","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/perfiles-del-firewall-de-windows\/"},"modified":"2024-03-04T18:46:43","modified_gmt":"2024-03-04T18:46:43","slug":"perfiles-del-firewall-de-windows","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/perfiles-del-firewall-de-windows\/","title":{"rendered":"Script PowerShell para activar o desactivar perfiles del firewall de Windows"},"content":{"rendered":"<p>Garantizar la seguridad de redes y sistemas es una prioridad en TI y una de las principales defensas en un entorno Windows es el Firewall de Windows, que se encarga de controlar el flujo de tr\u00e1fico entrante y saliente, actuando como portero. Este art\u00edculo profundiza en un <strong>script de PowerShell que <\/strong><strong>proporciona <\/strong><strong>un m\u00e9todo simplificado para activar o desactivar los perfiles del Firewall de Windows<\/strong>, una tarea crucial para los profesionales de TI.<\/p>\n<h2>Antecedentes<\/h2>\n<p>El script presentado est\u00e1 dise\u00f1ado para activar o desactivar todos los perfiles de red de Firewall de Windows: dominio, p\u00fablico y privado. Estos perfiles determinan la configuraci\u00f3n y las reglas que se aplican en funci\u00f3n del tipo de red al que est\u00e1 conectado un ordenador. Para los proveedores de servicios gestionados (MSP) y los profesionales de TI, una herramienta que pueda alternar r\u00e1pidamente estos perfiles tiene un valor incalculable. Ya sea para solucionar problemas, reforzar la seguridad o configurar la red, este script ofrece una soluci\u00f3n r\u00e1pida.<\/p>\n<h2>El script para activar o desactivar perfiles del Firewall de Windows<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Enable or disable all Windows Firewall profiles(Domain, Public, Private).\r\n.DESCRIPTION\r\n    Enable or disable all Windows Firewall profiles(Domain, Public, Private).\r\n.EXAMPLE\r\n     -Disable\r\n    Disables all Windows Firewall profiles(Domain, Public, Private).\r\n.EXAMPLE\r\n     -Enable\r\n    Enables all Windows Firewall profiles(Domain, Public, Private).\r\n.EXAMPLE\r\n     -Enable -BlockAllInbound\r\n    Enables all Windows Firewall profiles(Domain, Public, Private).\r\n    Blocks all inbound traffic on the Domain, Public, Private profiles\r\n.OUTPUTS\r\n    String[]\r\n.OUTPUTS\r\n    PSCustomObject[]\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes:\r\n    Initial Release\r\nBy 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.\r\n    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. \r\n    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. \r\n    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. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, 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. \r\n    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. \r\n    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. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n.COMPONENT\r\n    ProtocolSecurity\r\n#&gt;\r\n\r\n[CmdletBinding(DefaultParameterSetName = \"Enable\")]\r\nparam (\r\n    [Parameter(\r\n        Mandatory = $true,\r\n        ParameterSetName = \"Enable\"\r\n    )]\r\n    [Switch]\r\n    $Enable,\r\n    [Parameter(\r\n        Mandatory = $true,\r\n        ParameterSetName = \"Disable\"\r\n    )]\r\n    [Switch]\r\n    $Disable,\r\n    [Parameter(\r\n        ParameterSetName = \"Enable\"\r\n    )]\r\n    [Switch]\r\n    $BlockAllInbound\r\n)\r\n\r\nbegin {\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n}\r\nprocess {\r\n    if (-not $(Test-IsElevated)) {\r\n        Write-Error -Message \"Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n    if ($(Get-Command \"Get-NetFirewallProfile\" -ErrorAction SilentlyContinue).Name -like \"Get-NetFirewallProfile\") {\r\n        # Use Get-NetFirewallProfile if available\r\n        try {\r\n            $NetFirewallSplat = @{\r\n                Profile     = @(\"Domain\", \"Public\", \"Private\")\r\n                Enabled     = $(if ($Enable) { \"True\" }elseif ($Disable) { \"False\" })\r\n                ErrorAction = \"Stop\"\r\n            }\r\n            if ($Enable -and $BlockAllInbound) {\r\n                $NetFirewallSplat.Add('DefaultInboundAction', 'Block')\r\n                $NetFirewallSplat.Add('DefaultOutboundAction', 'Allow')\r\n            }\r\n            Set-NetFirewallProfile @NetFirewallSplat\r\n            \r\n        }\r\n        catch {\r\n            Write-Error $_\r\n            Write-Host \"Failed to turn $(if ($Enable) { \"on\" }elseif ($Disable) { \"off\" }) the firewall.\"\r\n            exit 1\r\n        }\r\n        # Proof of work\r\n        Get-NetFirewallProfile -ErrorAction Stop | Format-Table Name, Enabled        \r\n    }\r\n    else {\r\n        # Fall back onto netsh\r\n        netsh.exe AdvFirewall set AllProfiles state $(if ($Enable) { \"on\" }elseif ($Disable) { \"off\" })\r\n        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n        netsh.exe AdvFirewall set DomainProfile state $(if ($Enable) { \"on\" }elseif ($Disable) { \"off\" })\r\n        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n        netsh.exe AdvFirewall set PrivateProfile state $(if ($Enable) { \"on\" }elseif ($Disable) { \"off\" })\r\n        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n        netsh.exe AdvFirewall set PublicProfile state $(if ($Enable) { \"on\" }elseif ($Disable) { \"off\" })\r\n        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n        \r\n        if ($Enable -and $BlockAllInbound) {\r\n            try {\r\n                netsh.exe AdvFirewall set DomainProfile FirewallPolicy \"BlockInbound,AllowOutbound\"\r\n                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n                netsh.exe AdvFirewall set PrivateProfile FirewallPolicy \"BlockInbound,AllowOutbound\"\r\n                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n                netsh.exe AdvFirewall set PublicProfile FirewallPolicy \"BlockInbound,AllowOutbound\"\r\n                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n            }\r\n            catch {\r\n                Write-Error $_\r\n                Write-Host \"Could not set Block All Inbound Traffic to 1\"\r\n            }\r\n        }\r\n        # Proof of work\r\n        netsh.exe AdvFirewall show AllProfiles state\r\n        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }\r\n    }\r\n}\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Accede a m\u00e1s de 300 scripts en el Dojo de NinjaOne<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/es\/prueba-gratuita-formulario\/\">Obt\u00e9n acceso<\/a><\/p>\n<\/div>\n<h2>Desglose detallado<\/h2>\n<p>B\u00e1sicamente, el script comprueba si se dispone de privilegios de administrador, algo esencial ya que para modificar la configuraci\u00f3n del firewall se necesitan derechos elevados. A continuaci\u00f3n, comprueba la presencia del cmdlet Get-NetFirewallProfile, un moderno comando de PowerShell para gestionar perfiles de firewalls.<\/p>\n<p>Si este cmdlet est\u00e1 disponible, el script lo emplea para activar o desactivar los perfiles especificados. La opci\u00f3n de bloquear todo el tr\u00e1fico entrante y permitir el saliente a\u00f1ade una capa adicional de seguridad.<\/p>\n<p>En ausencia del cmdlet Get-NetFirewallProfile, el script vuelve a la antigua herramienta de l\u00ednea de comandos netsh.exe.<\/p>\n<h2>Posibles casos de uso<\/h2>\n<p>Imaginemos a Marta, profesional de TI en una multinacional. Est\u00e1n introduciendo una nueva aplicaci\u00f3n, pero durante las pruebas descubren que \u00e9sta no puede comunicarse con su servidor. Ante la sospecha de un problema con el firewall, Marta utiliza este script para desactivar temporalmente los perfiles del firewall, probar la aplicaci\u00f3n y, a continuaci\u00f3n, volver a activarlos. Esta acci\u00f3n r\u00e1pida ayuda a diagnosticar el problema sin navegaci\u00f3n manual.<\/p>\n<h2>Comparaciones<\/h2>\n<p>El script proporciona un enfoque program\u00e1tico para la gesti\u00f3n de perfiles de firewalls. Las alternativas incluyen el ajuste manual a trav\u00e9s de la GUI del Firewall de Windows o el uso de Objetos de Directiva de Grupo (GPO) para m\u00e1quinas unidas a un dominio. Sin embargo, ninguno cuenta con la inmediatez de este script.<\/p>\n<h2>Preguntas frecuentes<\/h2>\n<ul>\n<li>\u00bfPuedo ejecutar este script en cualquier equipo Windows?<br \/>\nEst\u00e1 dise\u00f1ado para Windows 10 y Windows Server 2016 y superiores.<\/li>\n<li>\u00bfNecesito permisos especiales para ejecutar este script?<br \/>\nS\u00ed, se necesitan privilegios de administrador.<\/li>\n<\/ul>\n<h2>Implicaciones para la seguridad<\/h2>\n<p>La posibilidad de cambiar r\u00e1pidamente los perfiles de firewall es un arma de doble filo. Desactivarlas, aunque sea moment\u00e1neamente, puede exponer los sistemas a amenazas. Es vital comprender las implicaciones para la seguridad y garantizar que los sistemas permanezcan protegidos.<\/p>\n<h2>Recomendaciones<\/h2>\n<ul>\n<li>Prueba el script en un entorno controlado primero.<\/li>\n<li>Si desactivas el firewall para realizar el diagn\u00f3stico, vuelve a activarlo inmediatamente despu\u00e9s.<\/li>\n<li>Relee peri\u00f3dicamente las reglas del firewall para garantizar su conformidad con las pol\u00edticas de seguridad.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>La gesti\u00f3n de los perfiles del Firewall de Windows es esencial para la seguridad de la red y del sistema. Mientras que herramientas como NinjaOne ofrecen <a href=\"https:\/\/www.ninjaone.com\/es\/\">soluciones integrales de gesti\u00f3n de TI<\/a>, scripts como el que acabamos de ver son muy valiosos para tareas espec\u00edficas. Como siempre, comprender su funcionamiento y sus implicaciones garantiza un uso eficaz y seguro.<\/p>\n","protected":false},"author":35,"featured_media":207103,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[4265],"class_list":["post-208619","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/208619","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=208619"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media\/207103"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=208619"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=208619"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=208619"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}