Looping, incrementing batch files

I occasionally need to do brute-force scans or commands on networks or computer names and have found many occasions to use a script similar to this.  It leverages loops in windows batch files, plus the ability to create and increment variables on the fly in a batch file.  (Note: this would be placed in a text file saved as “batchname.cmd” and executed from a command line )

@echo off
set /a var=1
:LOOP
if %var% gtr 254 goto :END
psexec \192.168.1.%var%  <command>
set /a var+=1
goto LOOP
:END

This leverages the psexec tool from the pstools suite.

line one, turn off useless messages echoed to the console with @echo off
line two, create a local variable “var” with an initial value of 1
line three, start a loop named “LOOP”
line four, check the variable “var” to  see if its value exceeds the desired limit (I typically want to scan all IPs from 1 to 254)
line five, run whatever you want leveraging the incremented variable
line six, add 1 to var
line seven, go back to the top
line eight, END

If you have eight computers named Computer1 – Computer8 start var at 1 with a limit of 8, execute your command targeting “computer%var%:

If you want to run something on IPs 192.168.1.100-200 start var at 100 with a limit of 200, execute your command targeting “192/168.1.%var%”

 

If you have a list that is not in order or have no numbers you can a simpler version:

@echo off
:LOOP
if !%1!==!! goto :END
psexec \%1%  <command>
shift
goto LOOP
:END

This command is based off of command line parameters, execute the batch file using “batch.cmd Smith Jones Obama Simpson” and it will execute the command using each of the names in order.

 

This entry was posted in Computing, Scripting and tagged . Bookmark the permalink.

2 Responses to Looping, incrementing batch files

  1. scott says:

    nice work. I was looking for a way to enter 1 ip address and the increment just the last octet , but the first 3 octets can be anything depending on which network im trying to fix. The problem with your example is that the first 3 octets are not changeable, any ideas?

Leave a Reply