Enable the windows firewall

Enable/disable firewall from command line

Windows firewall can be enabled/disabled from command line using netsh command.

Windows 10 / Windows 8/ Windows 7 / Server 2008 /Vista:

Let’s see the syntax of netsh advfirewall to configure firewall on these Windows versions. Firewall settings are different for each of the 3 networks(Domain, private, public). So based on which network firewall you want to enable/disable, the command would vary.

You can turn on firewall for the current network profile(does not matter if it’s domain/private/public network) using the below command.

Turn off firewall for the current profile:

These commands should be run from an elevated administrator command prompt. Otherwise you would get the below error.

To enable/disable firewall for a specific network profile, you can use the below commands.

Domain network

Turn on Domain network firewall:

Turn off domain network firewall:

Private network

Turn on private network firewall:

Turn off private network firewall:

Public network

Turn on public network firewall:

Turn off public network firewall:

Configure for all networks

Turn on firewall for all networks

Turn off firewall for all networks

Older Windows versions – XP / Server 2003:

Below is the command to turn on firewall.

The command to turn off firewall is:

Administrator privileges are required to configure firewall so above command can be run only from admin accounts.

netsh firewall is deprecated in new versions.

In Windows 10/ 8 / 7 / Vista/ Server 2008, ‘netsh firewall‘ command prints message like below.

running it from normal cmd give this error.

Open cmd as with ‘run as adminitrator’ option.

Awesome article, Thank you very much

Thank you very much

Thanks A lot for sharing knowledge
Wanna add note :
the old command netsh.exe firewall set opmode disable or enable this command was Used only with Public profile for windows to set it on Or off . But The new Command Specially this : Netsh.exe advfirewall set allprofiles state on (Perfect Command)
Really …… Thanks too much for sharing this I spent a long time in searching for such this this command because it’s Comprehensive for security issue .

Typo:
Turn on public network firewall:
netsh advfirewall set publicprofile state on
Turn on public network firewall:
__
netsh advfirewall set publicprofile state off
Just trying to help

Thank you very much

First article that solves all my issues with clear exampls

How to enable or disable the Microsoft Windows Firewall

Many users are interested in either enabling or disabling their Windows Firewall for various reasons. Some users want to utilize a different firewall, and some may have turned theirs off by accident. To proceed, select your version of Windows from the list below and follow the instructions.

Читайте также:  Webrtc клиент для windows

Windows 8 and 10

If you’re looking to disable a firewall other than the one that comes with Windows, see: How do I disable the firewall program installed on my computer?

Disabling the Windows 8 or 10 firewall

Unless you are troubleshooting an issue or plan on installing another firewall, we recommend you don’t disable the Windows Firewall.

If you’re disabling the firewall because a program can’t access the Internet, see: How to open a port for program or game in Windows Firewall.

  1. Press the Windows key , type Windows Defender Firewall, and then press Enter .
  2. On the left side of the screen, under Control Panel Home, select Turn Windows Defender Firewall on or off.

  1. In the Customize Settingswindow, click the circle(s) next to Turn off Windows Defender Firewall for public networks, private networks, or both.

  1. When you’re finished, click the button.

Enabling Windows 8 or 10 firewall

Only one software firewall should be enabled at a time. If you have an antivirus or other security program installed with its own firewall, make sure it is disabled first.

  1. Press the Windows key , type Windows Defender Firewall, and then press Enter .
  2. On the left side of the screen, under Control Panel Home, select Turn Windows Defender Firewall on or off.

  1. In the Customize Settings window, click the circle(s) next to Turn on Windows Defender Firewall for public networks, private networks, or both.

  1. When you’re finished, click the button.

Enable and disable the firewall in Windows Vista and Windows 7

Microsoft Windows Vista and 7 come pre-installed with a firewall utility, although it may be disabled by default. Below are steps that can be followed to enable or disable the firewall in Windows. If you’re looking to disable a different firewall, see: How do I disable the firewall program installed on my computer?

Disabling the Windows Vista and Windows 7 firewall

Unless you are troubleshooting an issue or plan on installing another firewall, we recommend you don’t disable your Windows Firewall.

If you’re disabling the firewall because a program can’t access the Internet, see: How to open a port for program or game in Windows Firewall.

  1. Click Start and in the Search for Programs and Files text box, type firewall, and press Enter .
  2. In the search results, click Windows Firewall.
  3. If the Windows Firewall is enabled, the Windows Firewall state will be «on.» To turn it off, click Change settings or Turn Windows Firewall on or off in the left column.
  4. In the Firewall Settings window, select Off and click OK.

Enabling Windows Vista and Windows 7 firewall

Only one software firewall should be enabled at a time. If you have an antivirus or other security program installed with its own firewall, make sure it is disabled first.

  1. Click Start and in the Search for Programs and Files text box, type firewall, and press Enter .
  2. In the search results, click Windows Firewall.
  3. If the Windows Firewall is disabled, the Windows Firewall state will be off. If it is off, click Change settings or Turn Windows Firewall on or off in the left column.
  4. In the Firewall Settings window, select On and click OK.
Читайте также:  Windows 10 отключение обновлений 1903

Enable and disable the firewall in Windows XP

Although Microsoft Windows XP comes with a pre-installed firewall utility, by default, this feature is not enabled. Below are steps that can be followed to enable or disable this feature in Windows XP. If you’re looking for information about disabling a firewall other than that which comes with Windows, see: How do I disable the firewall program installed on my computer?

Disabling the Windows XP firewall

Unless you are troubleshooting an issue or plan on installing another firewall, we recommend you don’t disable your Windows Firewall.

If you’re disabling the firewall because a program can’t access the Internet, see: How to open a port for program or game in Windows Firewall.

  1. Open the Control Panel
  2. Open Network Connections.
  3. In the Network Connectionswindow, right-click the Local Area Connection and select Properties.
  4. In the Local Area Connection Properties window, click the Advancedtab.
  5. Finally, uncheck the Protect my computer and network by limiting or preventing access to this computer from the Internet option.

If you’re attempting to disable the Windows XP firewall, but this option is already unchecked, another developer’s firewall program may be installed on the computer.

Enabling the Windows XP firewall

Only one software firewall should be enabled at a time. If you have an antivirus or other security program installed with its own firewall, make sure it is disabled first.

Управление правилами Windows Firewall с помощью PowerShell

Эта статья посвящена основам управления настройками и правилами встроенного Windows Firewall из командной строки PowerShell. Мы рассмотрим, как включать/отключать брандмауэр для различных профилей, создавать и удалять правила файервола, и рассмотрим небольшой скрипт, позволяющий сформировать удобную таблицу с текущим набором активных правил брандмауэра.

Вы можете управлять настройками Windows Firewall из графической консоли Control Panel -> System and Security -> Windows Defender Firewall. Однако начиная с Windows 8.1 (Windows Server 2012R2) для управления встроенным брандмауэром в систему был добавлен встроенный PowerShell модуль NetSecurity.

В модуле NetSecurity в Windows 10 доступно 85 команд. Вы можете вывести их список:

Get-Command -Module NetSecurity

Управление сетевыми профилями брандмауэра Windows из PowerShell

В Windows Firewall есть три типа сетевых профилей:

  • Domain (Доменный) – применяется к компьютерам, включенным в домен Active Directory;
  • Private (Частный) – домашние или рабочие сети;
  • Public (Общий) – общедоступные сети.

Каждый профиль может отличаться используемым набором правил файервола. По умолчанию все сетевые интерфейсы компьютера защищены фаейрволом и к ним применяются все три типа профилей.

Чтобы включить все три сетевых профиля Domain, Public и Private, используйте команду:

Set-NetFirewallProfile -All -Enabled True

Либо укажите конкретный профиль вместо All:

Set-NetFirewallProfile -Profile Public -Enabled True

Чтобы отключить файервол для всех трех сетевых профилей, используется команда:

Set-NetFirewallProfile -All -Enabled False

С помощью командлета Set-NetFirewallProfile вы можете изменить параметры профиля (действие по-умолчанию, журналирование, путь и размер файла журнала, настройки оповещений и т.д.).

Как вы вероятно знаете, по умолчанию Windows Firewall включен в современных ОС для всех профилей. В настройках профилей разрешены все исходящие подключения и блокируется входящие (кроме разрешенных).

Изменим действие по-умолчнию для профиля Public – заблокировать все входящие подключения.

Set-NetFirewallProfile –Name Public –DefaultInboundAction Block

Текущие настройки профиля можно вывести так:

Читайте также:  Hp laserjet pro mfp m127fw драйвер mac os

Get-NetFirewallProfile -Name Public

Если вы управляете настройками Windows Firewall через GPO, вы можете вывести текущие результирующие настройки профилей так:

Get-NetFirewallProfile -policystore activestore

Проверим, что все параметры брандмауэра применяются ко всем сетевым интерфейса компьютера.

Get-NetFirewallProfile -Name Public | fl DisabledInterfaceAliases

Если все интерфейсы защищены, команда должна вернуть:

Можно отключить определенный профиль для интерфейса (вывести список имен интерфейсов можно с помощью командлета Get-NetIPInterface).

Set-NetFirewallProfile -Name Public -DisabledInterfaceAliases «Ethernet0»

Как вы видите, теперь профиль Public не применяется к интерфейсу Ethernet0:

Вы можете настроить параметры логирования сетевых подключений на уровне каждого профиля. По умолчанию журналы Windows Firewall хранятся в каталоге %systemroot%\system32\LogFiles\Firewall, размер файла – 4 Мб. Вы можете изменить включить журналирование подключений и увеличить максимальный размер файла:

Set-NetFireWallProfile -Profile Domain -LogBlocked True -LogMaxSize 20000 -LogFileName ‘%systemroot%\system32\LogFiles\Firewall\pfirewall.log’

Создание, редактирование и удаление правил Windows Firewall из PowerShell

Для управления правилами брандмауэра есть 9 командлетов:

  • New-NetFirewallRule
  • Copy-NetFirewallRule
  • Disable-NetFirewallRule
  • Enable-NetFirewallRule
  • Get-NetFirewallRule
  • Remove-NetFirewallRule
  • Rename-NetFirewallRule
  • Set-NetFirewallRule
  • Show-NetFirewallRule

Рассмотрим несколко простых примеров открытия портов в Windows Firewall.

Например, вы хотите разрешить входящие TCP подключения на порты 80 и 443 для профилей Domain и Private, воспользуйтесь такой командой:

New-NetFirewallRule -DisplayName ‘WEB-Inbound’ -Profile @(‘Domain’, ‘Private’) -Direction Inbound -Action Allow -Protocol TCP -LocalPort @(’80’, ‘443’)

Вы можете разрешить или заблокировать трафик для конкретной программы. Например, вы хотите заблокировать исходящие соединения для FireFox:

New-NetFirewallRule -Program “C:\Program Files (x86)\Mozilla Firefox\firefox.exe” -Action Block -Profile Domain, Private -DisplayName “Block Firefox” -Description “Block Firefox” -Direction Outbound

Разрешим входящее RDP подключение по порту 3389 только с IP одного адреса:

New-NetFirewallRule -DisplayName «AllowRDP» –RemoteAddress 192.168.1.55 -Direction Inbound -Protocol TCP –LocalPort 3389 -Action Allow

Чтобы разрешить ping для адресов из указанной подсети, используйте команды:

$ips = @(«192.168.1.50-192.168.1.60», «192.165.2.22-192.168.2.200», ”10.10.0.0/16”)

New-NetFirewallRule -DisplayName «Allow inbound ICMPv4» -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -RemoteAddress $ips -Action Allow

New-NetFirewallRule -DisplayName «Allow inbound ICMPv6» -Direction Inbound -Protocol ICMPv6 -IcmpType 8 -RemoteAddress $ips -Action Allow

Чтобы отредактировать имеющееся правило брандмауэра, используется командлет Set-NetFirewallRule. Например, вы хотите разрешить входящие подключения с указанного IP адреса для ранее созданного правила:

Get-NetFirewallrule -DisplayName ‘WEB-Inbound’ | Get-NetFirewallAddressFilter | Set-NetFirewallAddressFilter -RemoteAddress 192.168.1.20

Если нужно добавить в правило файервола несколько IP адресов, используйте такой скрипт:

$ips = @(«192.168.1.50», «192.165.2.22»,”192.168.1.20”)

Get-NetFirewallrule -DisplayName ‘WEB-Inbound’|Set-NetFirewallRule -RemoteAddress $ips

Вывести все IP адреса, которые содержатся в правиле брандмауэра:

Get-NetFirewallrule -DisplayName ‘Allow inbound ICMPv4’|Get-NetFirewallAddressFilter

Вы можете включать/отключать правила файервола с помощью командлетов Disable-NetFirewallRule и Enable-NetFirewallRule.

Disable-NetFirewallRule –DisplayName ‘WEB-Inbound’

Чтобы разрешить ICMP (ping), выполните команду:

Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In

Чтобы удалить правило брандмауэре используется командлет Remove-NetFirewallRule.

Вывод правил Windows Firewall через PowerShell

Список активных правил для входящего трафика можно вывести так:

Если, например, нам нужно вывести список блокирующих исходящих правил:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound

Если нужно отобразить имя программы в правиле:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound | %

Как вы видите командлет Get-NetFirewallRule не выводит порты сетевые порты и IP адреса для правил брандмауэра. Чтобы вывести всю информацию о разрешенных входящих (исходящих) подключениях в более удобном виде с отображением номеров портов, используйте такой скрипт:

PowerShell предоставляет широкие возможности по управлению правилами Windows Firewall из командной строки. Вы можете автоматически запускать скрипты PowerShell для открытия/закрытия портов при возникновении определенных событий. В следующей статье мы рассмотрим простую систему на базе PowerShell и Windows Firewall для автоматической блокировки IP адресов, с которых выполняется удаленный перебор паролей по RDP на Windows VDS сервере.

Оцените статью