Windows Server 2022 防火墙如何添加动态IP
# 获取动态IP地址 $dynamicIp = ([System.Net.Dns]::GetHostAddresses("你的动态域名.com")).IPAddressToString # 定义端口列表 $ports = @(8877, 8899) foreach ($port in $ports) { $ruleName = "AllowPort$port" # 检查规则是否存在,如果不存在则创建规则 if (-not (Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue)) { New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Protocol TCP -LocalPort $port -Action Allow } # 更新防火墙规则,允许指定动态IP访问指定端口 Set-NetFirewallRule -DisplayName $ruleName -RemoteAddress $dynamicIp -Direction Inbound -Protocol TCP -LocalPort $port }
保存上述代码为UpdateFirewallIP.ps1
设置任务计划程序
为了让脚本定期运行以更新动态 IP,你可以使用任务计划程序:
打开 “任务计划程序”。可以通过在开始菜单中搜索 “任务计划程序” 来找到它。
在右侧面板中,点击 “创建任务”。
在 “常规” 选项卡中:
为任务命名,例如 Update Firewall IP。
选择 “使用最高权限运行”,确保脚本有足够的权限修改防火墙规则。
在 “触发器” 选项卡中:
点击 “新建”,设置触发任务的时间间隔,例如每天或每小时运行一次。
在 “操作” 选项卡中:
点击 “新建”,“操作” 选择 “启动程序”。
在 “程序 / 脚本” 中输入 powershell.exe。
在 “添加参数(可选)” 中输入 -ExecutionPolicy Bypass -File C:\Scripts\UpdateFirewallIP.ps1(根据实际脚本保存路径修改)。
点击 “确定” 保存任务。