WINDOWS下利用防火墙批量禁止垃圾邮件IP地址

2021/12/19 12:39:02      点击:

将下面的代码保存为一个BAT文件,比如:拒绝垃圾邮件.bat 然后创建一个SpamSourceIP.txt,在里面写入你需要拦截的IP地址,保存后执行拒绝垃圾邮件.bat即可。全自动去重复,太多IP都可以,自动分组。

@echo off

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

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