如何在PowerShell中添加端口例外?
美国、香港服务器
如何在PowerShell中添加端口例外?
07-08 来源:
一、常用场景命令
1. 放行单个 TCP 端口入站(例:443 HTTPS)
powershell
New-NetFirewallRule -DisplayName "允许TCP 443 HTTPS入站" `
-Direction Inbound -Protocol TCP -LocalPort 443 `
-Action Allow -Profile Any
2. 同时放行多个端口(80、443)
powershell
New-NetFirewallRule -DisplayName "Web 80/443 TCP入站" `
-Direction Inbound -Protocol TCP -LocalPort 80,443 `
-Action Allow -Profile Any
3. 放行端口区间(3000-3010)
powershell
New-NetFirewallRule -DisplayName "业务端口3000-3010 TCP入站" `
-Direction Inbound -Protocol TCP -LocalPort 3000-3010 `
-Action Allow -Profile Any
4. 放行 UDP 端口(如 500、4500 VPN)
powershell
New-NetFirewallRule -DisplayName "VPN UDP 500/4500" `
-Direction Inbound -Protocol UDP -LocalPort 500,4500 `
-Action Allow -Profile Any
5. 出站端口例外(服务器程序访问外网 443)
powershell
New-NetFirewallRule -DisplayName "出站允许TCP 443" `
-Direction Outbound -Protocol TCP -LocalPort 443 `
-Action Allow -Profile Any
二、生产安全加固:仅允许指定 IP 访问端口(禁止全网开放)
示例:仅你的办公公网 IP 110.10.10.10 访问 443
powershell
New-NetFirewallRule -DisplayName "443仅信任IP访问" `
-Direction Inbound -Protocol TCP -LocalPort 443 `
-RemoteAddress "110.10.10.10/32" `
-Action Allow -Profile Any
多 IP / 网段逗号分隔
powershell
-RemoteAddress "110.10.10.10/32,192.168.1.0/24"
三、防火墙规则管理常用命令
1. 查询已放行 443 端口规则
powershell
Get-NetFirewallRule | Where-Object {$_.LocalPort -eq "443"}
2. 禁用某条规则
powershell
Disable-NetFirewallRule -DisplayName "允许TCP 443 HTTPS入站"
3. 启用禁用的规则
powershell
Enable-NetFirewallRule -DisplayName "允许TCP 443 HTTPS入站"
4. 删除端口规则(清理无用例外)
powershell
Remove-NetFirewallRule -DisplayName "允许TCP 443 HTTPS入站"
5. 修改已有规则,新增允许 IP
powershell
Set-NetFirewallRule -DisplayName "443仅信任IP访问" -RemoteAddress "110.10.10.10/32,203.0.0.5/32"
四、批量脚本示例(一次性开放 Web 全套端口)
powershell
# 80 入站
New-NetFirewallRule -DisplayName "TCP 80 HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow -Profile Any
# 443 入站
New-NetFirewallRule -DisplayName "TCP 443 HTTPS" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow -Profile Any
# 出站全部443放行
New-NetFirewallRule -DisplayName "出站TCP443" -Direction Outbound -Protocol TCP -LocalPort 443 -Action Allow -Profile Any
五、关键避坑点
云服务器双层防护:PowerShell 仅配置系统防火墙,还要去云控制台安全组同步放行对应端口,否则外网依旧拒绝访问。
-Profile Any 必须加上:云服务器网卡属于公用网络,不写这条外网流量仍会被拦截。
规则冲突:若存在同名Block阻止规则,阻止优先级高于允许,需删除阻止规则。
第三方安全软件(安全狗 / 火绒 / EDR)有独立网络拦截,系统防火墙放行后不通,需在安全软件添加端口白名单。
六、端口连通验证(客户端 PowerShell)
powershell
Test-NetConnection 服务器公网IP -Port 443
输出 TcpTestSucceeded: True 代表端口放行成功。
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快