WINDOWS批量添加IP到防火墙

2021/12/19 10:20:22      点击:

代码是从国外的网站找到的,非常不错,WINDOWS2008开始到最新的系统,全部都支持,将下面的代码保存为 BAT格式即可。在相同目录下,创建一个BlackIPList.txt,把全部要屏蔽的IP地址写进去,双击BAT文件就自动添加完毕。WIN下远程IP只能200一组,下面的程序会自动拆分200一组加入黑名单屏蔽。以后只需要维护BlackIPList.txt就可以了,添加了新的IP再执行一次即可,程序会自动重新添加,非常的简单方便。

@echo off

setlocal enabledelayedexpansion
if "%1"=="list" (
  SET /A RULECOUNT=0
  for /f %%i in ('netsh advfirewall firewall show rule name^=all ^| findstr BlackListed') do (
    SET /A RULECOUNT+=1
    netsh advfirewall firewall show rule BlackListed!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 BlackListed') do (
  SET /A RULECOUNT+=1
  netsh advfirewall firewall delete rule name="BlackListed!RULECOUNT!"
)
SET "RULECOUNT="

REM Block new ips (while reading them from BlackListed.txt)
SET /A IPCOUNT=0
SET /A BLOCKCOUNT=1
for /f %%i in (BlackIPList.txt) do (
  SET /A IPCOUNT+=1
  if !IPCOUNT! == 201 (
    netsh advfirewall firewall add rule name="BlackListed!BLOCKCOUNT!" protocol=any dir=in 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="BlackListed!BLOCKCOUNT!" protocol=any dir=in 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