Configure Firewall Rules Using Windows Command Prompt


πŸ‘€Β Diwas Poudel Β Β  πŸ•’ 03 Aug 2024 Β Β  πŸ“ TECH

As we know, we can easily configure Windows Firewall using GUI-based configuration, but if you are an IT professional, you might want to know how to perform the same task using the command line. If that's the case, you are in the right place.

Why to use Command line for Configuration of Firewall ?

You can create scripts to apply multiple rules at once, which can be useful for deploying the same settings across many machines and servers. Additionally, this command line can be integrated into automated workflows, making management tasks easier.

Here, we will use the popular netsh command to perform this task. Now, let’s see how to do it:

Adding New Rules

Open Command Prompt as administrator and then in command line type below command:

netsh advfirewall firewall add rule name=<rule_name> protocol=<TCP/UDP> dir=<in/out> localport=<port> action=<allow/block>

Lets look this in syntax in summary.

  • name : Give the name of the rule.Β 
  • protocol : Protocol either TCP or UDP
  • dir : Direction of traffic either "in" for incoming or "out" for outgoing
  • localport : Port number you want to allow or block
  • action : Either Allow or Block the traffic.

Here is the sample example:

netsh advfirewall firewall add rule name="Allow HTTP 8080" protocol=TCP dir=in localport=8080 action=allow

This rules allow incoming TCP traffic on port 8080 and name of the rule is "Allow HTTP 8080".

You can see this in action:

Β  Fig. You can see that I have run the above command in action.

After running the above command, you can check the firewall in the UI and find that these rules have been successfully added.

Β  Β  fig. Rules added successfully

If you want to block the traffic then set action = block as shown below

netsh advfirewall firewall add rule name="Allow HTTP 8080" protocol=TCP dir=in localport=8080 action=block

Deleting Rule

You have to open command prompt as administrator then you have to perform following command

netsh advfirewall firewall delete rule name=<rule_name>

Replace rule_name with actual rule name in previous case it is "Allow HTTP 8080"

So if you want to delete the rules you have created above then apply following command:

netsh advfirewall firewall delete rule name="Allow HTTP"