我正在使用以下脚本来阻止ip从文本文件进入
Windows防火墙.
我正在使用Windows 2008 R2
@echo off if "%1"=="list" ( netsh advfirewall firewall show rule Blockit | findstr RemoteIP exit/b ) :: Deleting existing block on ips netsh advfirewall firewall delete rule name="Blockit" :: Block new ips (while reading them from blockit.txt) for /f %%i in (blockit.txt) do ( netsh advfirewall firewall add rule name="Blockit" protocol=any dir=in action=block remoteip=%%i netsh advfirewall firewall add rule name="Blockit" protocol=any dir=out action=block remoteip=%%i ) :: call this batch again with list to show the blocked IPs call %0 list
问题是,此脚本为每个被阻止的IP创建了一个单独的规则.
有没有办法在同一规则上禁止多个ips创建更少的规则?据我记得,每条规则最多允许200个被禁止的ips.因此,当找到ip number 201时,它应该创建一个新规则.这样,如果我们有1000个ips来阻止,它将只创建5条规则x 200 ip每条规则而不是1000条规则.
希望有人可以帮助我.谢谢
对于简单的<首先需要迭代200个IP并将所有IP地址转换为单个字符串.然后,您可以在循环外调用netsh命令两次(一次用于入站流量,一次用于出站流量). 为了让它能够处理200多个IP,我在for循环中添加了一个计数器.一旦超过200个IP,它将调用netsh命令并重置IP计数器,然后继续循环访问该文件.最终结果应该是您以“Blockitn”格式结束一系列规则,其中n是数字. 我不确定的一个部分是顶部的列表和删除指令.为了使这些工作正常,脚本需要知道存在多少相关的“Blockit”规则.我能想到的最好的方法是列出这些并通过for循环中的findstr传递结果.我不确定它是否正常工作.我会继续努力,但我想我会发布这个,因为它几乎就在那里 – 并希望你可能能够找到最后一点:) 请注意,在顶部附近添加了enabledelayedexpansion指令 – 这让我们可以使用!VAR!在初始化期间不会扩展的样式变量;只在执行时否则,最终的IPADDR变量将只包含文本文件中的最后一个IP.
原文链接:https://www.f2er.com/windows/367701.html@echo off setlocal enabledelayedexpansion if "%1"=="list" ( SET /A RULECOUNT=0 for /f %%i in ('netsh advfirewall firewall show rule name^=all ^| findstr Blockit') do ( SET /A RULECOUNT+=1 netsh advfirewall firewall show rule Blockit!RULECOUNT! | findstr RemoteIP ) SET "RULECOUNT=" exit/b ) REM Deleting existing block on ips SET /A RULECOUNT=0 for /f %%i in ('netsh advfirewall firewall show rule name^=all ^| findstr Blockit') do ( SET /A RULECOUNT+=1 netsh advfirewall firewall delete rule name="Blockit!RULECOUNT!" ) SET "RULECOUNT=" REM Block new ips (while reading them from blockit.txt) SET /A IPCOUNT=0 SET /A BLOCKCOUNT=1 for /f %%i in (blockit.txt) do ( SET /A IPCOUNT+=1 if !IPCOUNT! == 201 ( netsh advfirewall firewall add rule name="Blockit!BLOCKCOUNT!" protocol=any dir=in action=block remoteip=!IPADDR! netsh advfirewall firewall add rule name="Blockit!BLOCKCOUNT!" protocol=any dir=out action=block remoteip=!IPADDR! SET /A BLOCKCOUNT+=1 SET /A IPCOUNT=1 set IPADDR=%%i ) else ( if not "!IPADDR!" == "" ( set IPADDR=!IPADDR!,%%i ) else ( set IPADDR=%%i ) ) ) REM add the final block of IPs of length less than 200 netsh advfirewall firewall add rule name="Blockit!BLOCKCOUNT!" protocol=any dir=in action=block remoteip=!IPADDR! netsh advfirewall firewall add rule name="Blockit!BLOCKCOUNT!" protocol=any dir=out action=block remoteip=!IPADDR! SET "IPCOUNT=" SET "BLOCKCOUNT=" SET "IPADDR=" REM call this batch again with list to show the blocked IPs call %0 list
顺便说一句,如果是我,我可能会想要为这种事情学习Powershell(或者实际上是在半现代微软平台上编写任何脚本).一旦掌握了它,你会发现它比批处理文件更直观.