如何在PowerShell中创建新的防火墙规则?
美国、香港服务器
如何在PowerShell中创建新的防火墙规则?
08-07 来源:
基础语法
powershell
New-NetFirewallRule `
-DisplayName "规则显示名称" `
-Direction Inbound ` # Inbound入站 / Outbound出站
-Action Allow ` # Allow允许 / Block阻止
-Protocol TCP `
-LocalPort "端口" `
-RemoteAddress "来源IP" ` # Any=所有IP
-Enabled True `
-Profile Any # Any=域/专用/公用全部生效
常用模板(直接复制修改参数即可)
模板 1:放行端口,允许所有 IP 访问(最常用,例如放行 SSH 22 端口)
powershell
New-NetFirewallRule `
-DisplayName "放行SSH 22端口" `
-Direction Inbound `
-Action Allow `
-Protocol TCP `
-LocalPort 22 `
-RemoteAddress Any `
-Enabled True `
-Profile Any
模板 2:仅允许指定 IP访问端口(限制来源 IP)
powershell
New-NetFirewallRule `
-DisplayName "仅允许114.xx.xx.xx访问3389" `
-Direction Inbound `
-Action Allow `
-Protocol TCP `
-LocalPort 3389 `
-RemoteAddress "114.22.33.44" `
-Enabled True `
-Profile Any
多个 IP 用英文逗号分隔:
-RemoteAddress "1.1.1.1,2.2.2.2"
支持网段:192.168.1.0/24
模板 3:拉黑单个 IP(阻止指定外部 IP 访问本机,入站阻止)
注意:Windows 防火墙拉黑是直接阻断 TCP 握手,和安全狗中途断开连接表现不一样
powershell
New-NetFirewallRule `
-DisplayName "拉黑恶意IP 120.xx.xx.xx" `
-Direction Inbound `
-Action Block `
-Protocol Any `
-RemoteAddress "120.12.34.56" `
-Enabled True `
-Profile Any
模板 4:多端口一次性放行
powershell
New-NetFirewallRule `
-DisplayName "放行80、443端口" `
-Direction Inbound `
-Action Allow `
-Protocol TCP `
-LocalPort "80,443" `
-RemoteAddress Any `
-Enabled True `
-Profile Any
模板 5:范围端口(例如 8000-9000)
powershell
New-NetFirewallRule `
-DisplayName "放行8000-9000端口" `
-Direction Inbound `
-Action Allow `
-Protocol TCP `
-LocalPort "8000-9000" `
-RemoteAddress Any `
-Enabled True `
-Profile Any
模板 6:出站规则(限制服务器主动对外访问)
powershell
New-NetFirewallRule `
-DisplayName "阻止服务器对外访问外部80端口" `
-Direction Outbound `
-Action Block `
-Protocol TCP `
-RemotePort 80 `
-Enabled True `
-Profile Any
重要参数说明
表格
参数 说明
-DisplayName 防火墙界面展示的名称(修改 / 删除规则靠它识别,名称不要重复)
-Direction Inbound 外部机器访问服务器(绝大多数场景用这个)
-Action Allow / Block 允许 / 阻止
-Protocol TCP / UDP / Any
-LocalPort 服务器本机端口
-RemoteAddress 外部访问者 IP;Any= 不限
-RemotePort 对方机器端口(出站规则使用)
-Profile Any 在公用、专用、域网络全部生效
操作校验
创建完成后,执行命令验证规则是否生成:
powershell
Get-NetFirewallRule -DisplayName "规则显示名称" | Format-List *
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快