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 Windows Firewall. For most IT environments, using Group Policy is the easiest way to configure Windows Firewall on client computers.
It is also the easiest way to add port exceptions for services like HTTP, file sharing, software applications, etc. However, it is also useful to know how to configure Windows Firewall from the command line in case you have computers and servers that not in Active Directory.
Manage Windows Firewall from Command Prompt
First, to find out if Windows Firewall is enabled on the server or computer, enter the following command at a command prompt:
netsh advfirewall show allprofiles
Make sure to open an Administrator Command Prompt (click Start, type CMD, then right-click Command Prompt and select Run as Administrator). You should have something similar to what is shown below:
By default, you should see three separate lists here: domain profile settings, personal profile settings, and public profile settings. These three correspond to three states in which you can place every network connection on your computer. If you are connected to a home network and have selected the Home Network option, the private profile settings will be applied.
Status means whether the firewall is enabled. The firewall policy tells you which inbound and outbound policies are applied to each profile.
To disable the firewall for a specific profile, you must use the following command:
netsh advfirewall disable private profile status
Other options are current profile, general profile, domain profile, and all profiles. Therefore, if you want to disable the firewall completely, you should use allprofiles instead of privateprofile. To turn it back on, just put at the end, not turn it off.
Open the port in the firewall using the command line
What if you want to open a port in the firewall using the command line? It’s easy too!
Let’s say you want to open port 3389, which is for Remote Desktop on Windows. You just run this command:
netsh advfirewall firewall add rule name = “Open Remote Desktop” protocol = TCP dir = in localport = 3389 action = allow
The command is quite long, but rather easy to break. You add a rule, give it a name, select a protocol (TCP or UDP), select a direction (In or Out), assign a port number to it, and select an action (Allow or Deny).
If you run this command and then look at the allowed applications in Windows Firewall, you will see that the “Remote Desktop” item is now checked:
If you need to open a range of ports, just use a simple dash. For example, here I open ports 600o to 7000 for outgoing UDP traffic:
netsh advfirewall firewall add rule name = “UDP ports” protocol = UDP dir = out localport = 6000-7000 action = allow
There are many more additional commands that can be used to control all aspects of Windows Firewall, so be sure to use /? symbols at the end of any command to see all options and examples.