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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15171255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:19:14  来源:igfitidea点击:

How to open ports on Windows firewall through batch file

windowsbatch-filecmdportfirewall

提问by Stephane Grenier

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.

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

回答by Kevin Richardson

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

使用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

回答by Maxim Eliseev

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

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

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