Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open ports on Windows firewall through batch file

Is there any way within a batch file to open up specific ports on Windows through a batch file? It would be nice to have the installer do this for our server application rather than having the user manually do it.

like image 205
Stephane Grenier Avatar asked Mar 02 '13 05:03

Stephane Grenier


2 Answers

Use netsh.exe. A very simple batch file that takes a port argument:

@echo off
rem -- open port (first argument passed to batch script)
netsh advfirewall firewall add rule name="Open Port %1" dir=in action=allow protocol=TCP localport=%1 remoteip=10.15.97.0/24,10.17.0.0/16
like image 80
Kevin Richardson Avatar answered Oct 02 '22 16:10

Kevin Richardson


This is an extension of solution provided by @Kevin Richardson. Note that "netsh advfirewall add rule" command will create a new rule with the same name every time you run the same command. The script below helps to prevent it

ECHO OFF
set PORT=8081
set RULE_NAME="Open Port %PORT%"

netsh advfirewall firewall show rule name=%RULE_NAME% >nul
if not ERRORLEVEL 1 (
    rem Rule %RULE_NAME% already exists.
    echo Hey, you already got a out rule by that name, you cannot put another one in!
) else (
    echo Rule %RULE_NAME% does not exist. Creating...
    netsh advfirewall firewall add rule name=%RULE_NAME% dir=in action=allow protocol=TCP localport=%PORT%
)
like image 45
Maxim Eliseev Avatar answered Oct 02 '22 14:10

Maxim Eliseev