Thursday, April 24, 2014

Batch file: Ping IP’s in a range and IF successful run following command


As normal this script can have a lot of applications. In my case I was having some issues with computers getting updated in DNS correctly during a major system upgrade. I wrote this little script to help ease the pain. What I’m doing is pinging every IP address in a range one time. If the results for that ping is successful then I’m using PSEXEC (part of PSTOOLS) to run a command, in this case ipconfig /registerdns to update the DNS registration. To use PSEXEC you will need to download PSTOOLS and add PSEXEC to your syetem32 directory. Before running this script you will want to ensure the user that is running the script has permissions to complete the desired commands on the remote machine. You can add credentials to the script (psexec –u username –p password \\hostname) however be very cautious in doing this as it will be sent out over your network in clear text and odds are that’s not something you want to do.

Here is the script written for use inside a batch file (.bat):

SET SUBNET=10.10.10

for /l %i in (50,1,250) do @ping %SUBNET%.%%i -n 1 | find "Reply" && (psexec  \\%SUBNET%.%%i ipconfig /registerdns & echo Attempt to register DNS for IP: %SUBNET%.%%i >>DNS_Updated.txt)

A few explanations about the script. The SUBNET variable is configuring the first three octets of the subnet you want to scan. Simple enough. In this example we are scanning subnet 10.10.10.x

(50,1,250) This sets the IP range we want to scan. So in this case we are scanning IP range 10.10.10.50 through 10.10.10.250. The first number sets the starting IP and the last number sets the ending IP for the range.

(psexec  \\%SUBNET%.%%i ipconfig /registerdns & echo Attempt to register DNS for IP: %SUBNET%.%%i >>DNS_Updated.txt)

This section is the, what to do if successful part. If the ping succeeds what actions should it take? You could just output a list of IP’s to a file, you could copy or remove files, register the DNS as I have here, whatever your need calls for.

Ok that’s it, customize and have fun! I welcome comments with any enhanced versions or variations you may come up with.

1 comment:

  1. Many thanks for your script,
    here is my small modification for many subnets with IP addresses in range 101-199.
    I've used ErrorCode from PING to run PSEXEC only on live addresses ;)

    @ECHO OFF
    SET BASENET=192.168
    SET ADUSR=admin-user-name
    SET ADPAS=admin-password
    FOR %%C IN (9,11,13,16,22,30,31,32,33) DO (
    FOR /L %%D IN (199,-1,101) DO (
    ping -n 1 %BASENET%.%%C.%%D
    if %ErrorLevel% EQU 0 (
    psexec -u %ADUSR% -p %ADPAS% \\%BASENET%.%%C.%%D -h regedit /S modify.reg
    ECHO PC at address %BASENET%.%%C.%%D with result %ErrorLevel% >output.txt
    )
    )
    )

    ReplyDelete