如何通过批处理文件在Windows防火墙上打开端口

时间:2013-03-02 05:53:18

标签: windows batch-file cmd port firewall

批处理文件中是否有任何方法可以通过批处理文件在Windows上打开特定端口?让安装程序为我们的服务器应用程序执行此操作而不是让用户手动执行此操作会很好。

2 个答案:

答案 0 :(得分:20)

使用netsh.exe。带有端口参数的非常简单批处理文件:

@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

答案 1 :(得分:10)

这是@Kevin Richardson提供的解决方案的扩展。 请注意" netsh advfirewall添加规则"每次运行相同的命令时,command将创建一个具有相同名称的新规则。下面的脚本有助于防止它

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%
)