- Enable/disable firewall from command line
- Windows 10 / Windows 8/ Windows 7 / Server 2008 /Vista:
- Domain network
- Private network
- Public network
- Configure for all networks
- Older Windows versions – XP / Server 2003:
- Настройка брандмауэра Windows из командной строки cmd
- Выключение и включение
- Разрешение протоколов
- Закрытие и открытие портов
- Ограничения по IP адресам
- Правила для приложений
- Комбинирования параметров
- Zone PC
- Настройка брандмауэра windows из командной строки
- Включение, выключение
- Правила на порты
- Ограничения по IP адресам
- Правила для приложений
- Комбинирования параметров
- Enable or Disable Windows Firewall from Command Prompt
- Manage Windows Firewall from Command Prompt
- Open Port in Firewall using Command Line
- How To Manage Windows Firewall From Command Line With Netsh Command?
- Interactive Shell
- Network Profiles
- List All Network Profiles
- Domain Profile
- Private Profile
- Public Profile
- Turn Off Firewall
- Turn On Firewall
- Turn On Firewall For All Network Profiles
- List Current Firewall Configuration
- Open Port
- Close Port
- Drop ICMP or Ping Packets
- Enable Log
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
Настройка брандмауэра Windows из командной строки cmd
Брандмауэром Windows можно управлять не только привычным всем способом — через окна панели управления. Командная строка Windows так же имеет команды для управления собственным файрволом операционной системы Microsoft.
Способ управления брандмауэром через командную строку имеет массу незаменимых преимуществ перед оконным способом. Если вы хорошо владеете командной строкой, то гораздо быстрей выполните необходимые настройки написав нужные команды в cmd, чем кликая курсором по окнам. К тому же, консольный способ дает возможность управлять брандмауэром удаленного компьютера незаметно для его пользователя.
Рассмотрим подробнее какие команды есть для настройки брандмауэра Windows из командной строки CMD.
Для управление брандмауэром с помощью команд, командную строку CMD необходимо запустить с правами администратора.
Выключение и включение
Выключение сетевых профилей:
Включение сетевых профилей:
Запрет всех входящих соединений и разрешение исходящих:
Разрешение протоколов
Следующее правило принимает входящий трафик по ICMP-протоколу, проще говоря разрешает ping:
Закрытие и открытие портов
Разрешение входящих протоколов TCP и UDP на 80 порт:
Запрет входящих протоколов на 80 порт:
Открыть диапозон портов для исходящего UDP трафика
Удаление правил по имени
Ограничения по IP адресам
правило ограничивающие подключение одно ip-адреса
Ограничение подключений с диапазона ip-адресов или сетей.
Правила для приложений
Разрешить соединения для программы MyApp.exe
Комбинирования параметров
Можно использовать длинные выражения путем комбинирования сразу нескольких параметров:
Мы создали правило, которое разрешает входящие соединения к приложению MyApp из сетей с ip-адресами 157.60.0.1,172.16.0.0/16 и доменным профилем сетевого подключения.
На официальном сайте Microsoft можно ознакомится с примерами сравнения старого контекста Windows XP и нового, который начал использоваться в Windows 7.
Zone PC
Настройка брандмауэра windows из командной строки
В Windows server 2008 (R2), а также в обычных Windows vista, 7, 8 есть встроенный брандмауэр (firewall). В этой статье расмотрим несколько примеров как создавать правила из командной строки, также эти команды можно использовать при написании своих пакетных сценариев cmd, bat, powershell.
Все команды нужно выполнять из коммандной строки cmd запущенной с правами администратора.
Включение, выключение
Включение отдельных профилей:
Выключение отдельных профилей:
Запретить все входяшие соединения и разрешить все исходяшие:
Правила на порты
Разрешить входящие TCP и UDP соединения для 80 порта:
Запретить входящие на 80 порт:
Открыть диапозон портов для исходящего UDP трафика
Удалять правила можно по имени
Ограничения по IP адресам
Правила можно ограничивать для работы только с одним ip:
Или ограничивать по подсетями причем можно использовать разный синтаксис:
Правила для приложений
Разрешить соединения для программы MyApp.exe
Комбинирования параметров
Параметры можно соединять в довольно сложные цепочки:
В данном случае мы создали правило для программы, которое работает при если компьютер подключен к доменну организации (profile=domain) и определенны три диапозона ip адресов.
Подробней о настройках брандмауэра можно прочитать на сайте микрософта там же есть отличия от сторого синтаксиса который использовался на Windows XP и Windows server 2003:
Часть примеров были взяты из статьи на английском языке:
Enable or Disable Windows Firewall from Command Prompt
Easiest way to add port exceptions or computers not in Active Directory
There may come a time when you need to write a script or remotely connect to a PC and run a command to enable or disable the Windows firewall. For most IT environments, using Group Policy is the easiest way to configure the Windows Firewall on client computers.
It’s also the easiest way to add port exceptions for services such as HTTP, file sharing, software applications, and more. However, it’s also good to know how to configure the Windows Firewall from the command prompt just in case you have computers and servers that are not in Active Directory.
Manage Windows Firewall from Command Prompt
First, to see whether the Windows Firewall is enabled on a server or computer, type this command at the command prompt:
Make sure you open an administrator command prompt (click on Start, type in CMD and then right-click on Command Prompt and choose Run as Administrator). You should get something similar to what is shown below:
By default, you should see three separate listings here: Domain profile settings, private profile settings and public profile settings. These three correspond to the three states you can place each network connection on your computer into. If you are connected to your home network and you chose the Home Network option, the Private profile settings will be applied.
State means if the firewall is turned on or off. The Firewall Policy tells you what inbound and outbound policies are being applied to each profile.
To disable the firewall for a specific profile, you would use the following command:
The other options are currentprofile, publicprofile, domainprofile, and allprofiles. So if you wanted to disable the firewall completely, you would use allprofiles instead of privateprofile. To enable again, just put on at the end instead of off.
Open Port in Firewall using Command Line
Now what if you want to open a port in the firewall using the command line? That’s simple too!
Let’s say you want to open port 3389, which is for remote desktop in Windows. You would simply run this command:
The command is quite long, but it’s fairly easy to break down. You add a rule, give it a name, choose the protocol (TCP or UDP), choose the direction (In or Out), give it the port number and choose the action (Allow or Deny).
If you were to run this command, then go view the allowed apps in Windows Firewall, you would see that the Remote Desktop item is now checked:
If you need to open up a range of ports, just use a simple dash. For example, here I am opening ports 600o to 7000 for UDP outbound traffic:
There are many more advanced commands you can use to manage all aspects of the Windows Firewall, so make sure to use the /? characters at the end of any command to see all the options and examples.
Founder of Help Desk Geek and managing editor. He began blogging in 2007 and quit his job in 2010 to blog full-time. He has over 15 years of industry experience in IT and holds several technical certifications. Read Aseem’s Full Bio
How To Manage Windows Firewall From Command Line With Netsh Command?
Windows firewall is a useful mechanism which is used to control network traffic and ports. There are different ways to manage Windows firewall like GUI, Powershell and MS-DOS. Today we will look in detail how to manage windows firewall from command line with a popular tool named netsh . Netsh is a built-in tool which exists all Windows versions like Windows Server 2008, Windows Server 2012, windows Server 2016, Windows 7, Windows 8 and Windows 10.
Help about netsh command can be printed with /? option.
Help
As we can see from the output netsh command provides a lot of network management features like Wlan, Bridge, Dhcp, Ras etc.
Interactive Shell
Netsh command can be used from command line just issuing commands. But there is also an interactive shell where the same commands can be used to manage network. While using interactive shell netsh command is eliminated. Interactive shell can be started just using netsh command like below.
Interactive Shell
There is also sub shells or modules where they can be used issuing command like advfirewall
Interactive Shell for netsh
Network Profiles
As we know Windows operating systems comes with built-in profiles where different network security settings are application according to these profiles. After the network connection is established Windows ask us what type of network is the connected network. We select one of the following profiles.
- Domain Profile
- Private Profile
- Public Profile
List All Network Profiles
All existing network profiles can be listed with advfirewall show allprofiles command like below.
List All Network Profiles
As we can see from command output following information about network profiles are provided.
- State show whether this profiles is available and useable
- Firewall Policy show Inbound and Outbound connection policy whether inbound or outbound connection can be made in this profile by default.
- Local Firewall Rules shows whether local firewall rules exists or Group Policy inherited.
- Local Con Sec Rules
- Inbound User Notification show if an inbound connection is established whether a notification will be shown users desktop
- Remote Management specifies whether remote management ports and mechanisms can be used.
- Logging is partition about creating logs.
- Log Allowed Connections shows the configuration whether allowed connections will be logged
- Log Dropped Connections shows the configuration whether dropped connections will be logged
- File Name specifies the path and name of the firewall log.
- Max File Size shows the size of a log file which can be the maximum
Domain Profile
Domain profile is designed Windows systems those are in the Windows Domain.
Private Profile
Private profile is designed to be used in private life areas like home or at friend where we can semi trust to the network and not controlled by domain controller.
Public Profile
Public profile is designed to be used in public areas where real security threads exists. These areas are libraries, cafe etc.
Turn Off Firewall
Windows firewall is by default enabled. Firewall rules are strict and generally do not give ability to run 3. party applications on different ports. Another scenario is we have all ready installed an end point security solution and we do not need Windows built-in firewall. We can simply turn off Firewall. This will disable firewall for currently active network profile.
Turn Off Firewall
Turn On Firewall
As we stated previous step firewall of Windows operating systems are enabled by default. But we may need to enable and start firewall in some situations. This will enable firewall for currently active network profile.
Turn On Firewall
Turn On Firewall For All Network Profiles
Previous steps turn on and off firewall for the current provide. We can also turn on firewall for all existing profile with the following command. This will turn on firewall for Domain, Private and Public Profiles for the default configuration.
Turn On Firewall For All Network Profiles
List Current Firewall Configuration
We have previously listed all existing profiles configurations. We can also list only current profile configuration.
List Current Firewall Configuration
Open Port
Now we can start the real firewall management operations. One of the most used command and feature is opening firewall port. We will specify the Layer 4 protocol type like TCP or UDP and the port number with related name for identifier. In this example we will enable the port number 443 and name it MyHttps .
Close Port
We may need to close a port to make our system more secure and fortify our system. We will use delete command to remove existing open ports or exceptions. In this example we remote the port number TCP 443 with the name of MyHttps .
Drop ICMP or Ping Packets
One of the most used technique to troubleshoot the network connectivity in IT environment is using ICMP packets in Ping mechanism. We generally ping remote system to decide whether the network is running and remote system is up. But this may create some security hole in critical environments. So disabling ping is the more secure way.
We can disable the ping and drop ICMP packets with the following command.
Enable Log
Logging creates structural information about the events occurred in the Windows firewall. These logs may provide information about users, remote IP addresses, ports and actions. Logs can be used for security related mechanisms like Log Collection and SIEM. We can enable logs with set logging command like below.
In this example we enable logging by specifying log file path, the maximum line count of log file and status. After the maximum line count is reached the old logs will be deleted.