Windows

Build Your Skills: Automate ping to test a range of IP addresses

Provides code explanations and scripting for a versatile ping automation tool that can handle multiple IP addresses

If you use the TCP/IP protocol on your network, chances are good that you’re familiar with the ping command. In this Daily Drill Down, I’ll show you how to develop a script that creates a utility I call the Ping Automation Tool. I’ll then go through the script and explain in layman’s terms how it functions—so you don’t have to be a programmer to create or understand the script.

Using ping for troubleshooting
As you know, ping is one of the most useful network debugging tools in your arsenal for verifying IP-level connectivity. When you’re having problems connecting one system to another on a TCP/IP network, you can use the ping command to test the connection between two systems. If the ping command gets a response, then the connection is good, and you can concentrate on other problems.

But what if you need to ping multiple computers? For example, suppose that all the computers on your network are statically assigned Class C IP addresses. Unfortunately, your network has changed faster than you’ve been able to document it, and you’ve lost track of which IP addresses are in use and which are available.

One way to gather that information would be to ping a range of IP addresses and log the results. If you get a response, the IP address is in use. If you don’t get a response, two possibilities arise: Either the IP address is available or the system assigned to it is turned off. Either way, this troubleshooting technique will allow you to narrow the scope of the problem. You can later make sure that all systems on the network are turned on when you run this test.

Why automate ping?
Unfortunately, manually running the ping command for each address in a range and then documenting the results is very time consuming.

If you’re running Windows 2000, there’s a way to automate pinging multiple addresses by using the For…In (Set)…Do command, along with the enhancements provided by Windows 2000 command extensions. Using this method from a command prompt has several drawbacks, though. First, you have to type the command using the proper syntax—one typo and the command won’t work properly. Second, the results of the operation are difficult to gather since you have to scroll through the command prompt window and scan through a seemingly endless stream of text to find the pertinent information.

Fortunately, the Windows Script Host and its scripting languages provide you with the tools to create a much more elegant solution for automating the process of pinging multiple computers. Furthermore, this solution will work on systems running Windows 95, Windows 98, Windows NT, and Windows 2000.

Choosing a scripting language
While the Windows Script Host natively supports both the VBScript and JScript scripting engines, I consider VBScript to be a more mainstream and robust scripting language. As such, I chose to develop the Ping Automation Tool in VBScript. However, it’s important to keep in mind that with a good understanding of the JScript language and syntax, you could just as easily create the Ping Automation Tool script in JScript.

Creating the Ping Automation Tool script
Now that you have a better idea of how the ping command works, let’s create the script. To begin, launch Notepad and type the Ping Automation Tool script shown in Listing A. Be sure that you type all the commands exactly as shown (but don’t type the line numbers; they are for reference only). If you don’t, the script won’t work correctly. When you’ve finished, save the file as PingAutomationTool.vbs.

If typing in lines of code isn’t your cup of tea, don’t worry; the PingAutomationTool.vbs script is available for download. To download the script, just click here.

Listing A: PingAutomationTool.vbs
  1. Dim FirstPrompt, ErrorMessage, FileSystem, NetworkNum, FirstNodeNum,
  2. Dim DotTest, LastNodeNum, Dummy, TheDate, TheTime, TheFile, NodeNum
  3. FirstPrompt = "Please enter the first three octets of the IP addresses you want to test." & vbCrLf & vbCrLf &_
  4. "Use the form 123.456.789." & vbCrLf & vbCrLf &_
  5. "Be sure to include the . after the last number."
  6. ErrorMessage = "Operation failed!" & vbCrLf & vbCrLf &_
  7. "You didn't include the . after the last number." & vbCrLf & vbCrLf &_
  8. "Please repeat the operation."
  9. TheDate = Date
  10. TheTime = Time
  11. Const ForWriting = 2, ForAppending = 8
  12. Set WshShell = WScript.CreateObject("WScript.Shell")
  13. Set FileSystem = CreateObject("Scripting.FileSystemObject")
  14. NetworkNum = InputBox(FirstPrompt,"Ping Automation Tool")
  15. If NetworkNum = "" Then Wscript.Quit
  16. DotTest = Right(NetworkNum,1)
  17. If DotTest <> "." Then
  18. Dummy = WshShell.Popup(ErrorMessage,0, "Ping Automation Tool",16)
  19. Wscript.Quit
  20. Else
  21. FirstNodeNum = InputBox("Enter the first node number in the test range:","Ping Automation Tool")
  22. If FirstNodeNum = "" Then Wscript.Quit
  23. LastNodeNum = InputBox("Enter the last node number in the test range:","Ping Automation Tool")
  24. If LastNodeNum = "" Then Wscript.Quit
  25. End If
  26. Dummy = WshShell.Popup ( "Building Ping File. Please Wait...",1,"Ping Automation Tool",64)
  27. If (FileSystem.FileExists("c:\Pingfile.txt")) Then
  28. Set TheFile = FileSystem.OpenTextFile("c:\Pingfile.txt", ForAppending, True)
  29. Else
  30. Set TheFile = FileSystem.OpenTextFile("c:\Pingfile.txt", ForWriting, True)
  31. End If
  32. TheFile.WriteBlankLines(1)
  33. TheFile.WriteLine("=========================================")
  34. TheFile.WriteLine(" Ping Automation Tool")
  35. TheFile.WriteLine("This Ping Session was run on: " & TheDate & " at " & TheTime)
  36. TheFile.WriteLine("Testing " & NetworkNum&FirstNodeNum & " thru " & NetworkNum&LastNodeNum)
  37. TheFile.WriteLine("=========================================")
  38. TheFile.WriteBlankLines(1)
  39. TheFile.Close
  40. For NodeNum = FirstNodeNum To LastNodeNum
  41. WshShell.Run "Cmd.exe /c Ping.exe -n 2 " &NetworkNum&NodeNum &" >> c:\Pingfile.txt", 2,True
  42. WshShell.Run "Cmd.exe /c Echo. >> c:\Pingfile.txt", 2,True
  43. WshShell.Run "Cmd.exe /c Echo ********************************** >> c:\Pingfile.txt", 2,True
  44. Next
  45. WshShell.Run "Notepad.exe c:\Pingfile.txt", 1,True
  46. Wscript.Quit

Script overview
The Ping Automation Tool is very focused in that its primary use will be to test a range of Class C IP addresses on a small to medium-size network to determine whether the addresses are in use or available. (Keep in mind that you can use the Ping Automation Tool to test ranges of Class A and Class B IP addresses as well, but you can only test one range of node addresses at a time.)

To do so, the Ping Automation Tool will prompt you to enter the network identifier, or the first three sets of numbers, commonly called octets, in the IP address. It will then prompt you to enter the first node number in the range to be tested. The script will also prompt you to enter the last node number in the range to be tested.

At this point, the Ping Automation Tool script will create or open a text file that it will use to compile the report. It will create a report header and begin compiling the results.

Here’s where the script gets interesting. Since the ping command is actually a DOS-based command, emulating it in VBScript isn’t possible. For this reason, I’ve configured the script to shell out to DOS and, in a series of commands reminiscent of a batch file, run the ping command and redirect the results to the same report file I created earlier with VBScript commands.

As you can see, the Windows Script Host can provide a more elegant alternative to DOS-based batch files, and it can work in concert with DOS-based commands to accomplish higher-level tasks that neither tool could provide on its own.

Studying the Ping Automation Tool script
Now that you’ve created the Ping Automation Tool script and have a good idea of how it works, let’s take a step-by-step look at the VBScript commands that make the script work.

Defining the variables
The first two lines of PingAutomationTool.vbs use the Dim statement to define the variables that the script uses. In doing so, the script will allocate space in memory that it will use to store information as it does its job.

I’ve chosen variable names that closely represent the information that the script stores in the variables, to make it easier to follow the script.

Initializing variables
In lines 3 through 11, the script initializes several of its variables. Lines 3 through 5 assign the text string that will make up the prompt in the first dialog box to a variable appropriately named FirstPrompt. Lines 6 through 8 assign the text string that will make up an error message in an error dialog box to the ErrorMessage variable.

The reason that I assign these messages to variables rather than simply including them in the commands that display the dialog boxes is twofold: First, these messages are displayed on multiple lines separated by spaces in the dialog boxes. By assigning them to variables, I can easily format the messages the way I want them to appear in the dialog boxes by using the vbCrLf constant, which stands for carriage return/line feed and is equivalent to pressing [Enter] at the end of a line. Second, using the variables in the commands that display the dialog boxes makes these commands cleaner and easier to keep straight. (Keep in mind that I could include the entire message in the commands that display the dialog boxes, but it would mean that the message would be on one line, which would make the command unwieldy and prone to errors that would be difficult to find.)

Lines 9 and 10 simply assign the current date and time to the variables TheDate and TheTime, respectively. These variables will be used in the report header.

In line 11, I establish a couple of constants I can use in the commands that work with the text file that will become the report. In this case, the constants use suitable names to replace numeric values, which will make it easier to tell at a glance what the goal of the text file command is.

Assigning object references
Lines 12 and 13 use the Set command to assign object references to variables. Once that occurs, you can use the variables to access the methods that the objects make available.

Line 12 activates all of the features of the Windows Script Host object model by linking the WshShell object and the Wscript object together, which ultimately provides you with direct access to the Windows Shell. Line 13 uses a Set command to assign the FileSystemObject object reference to the FileSystem variable, which provides you with the ability to access and manipulate files and folders.

Prompting for input and evaluating the results
In lines 14 through 25, the script prompts for input and evaluates the results. Line 14 uses the InputBox function along with the FirstPrompt variable to prompt you to enter the first three sets of numbers in the IP address and then assigns that string to the NetworkNum variable. Line 15 then tests to see whether you’ve actually typed in a number and clicked OK or clicked the Cancel button. If you clicked the Cancel button, the script calls the Windows Script Host’s built-in Quit method to terminate the script.

Line 16 will set up a test to see if you entered the first three sets of numbers in the IP address in the proper format as specified in the prompt—you must type a period (.) after the last number. To perform this test, I use the Right function to retrieve the right-most character in the string and then assign it to the DotTest variable.

The script then uses an If…Then…Else statement to test the character in the DotTest variable. If it’s not a period, the script uses the Popup method in line 18 to display an error message and then uses the Quit method to terminate the script. Because the Popup method is actually designed to return a result, I must assign that result to the Dummy variable even though I’ll never use it.

The reason for testing for the period character is twofold: First, it’s a required part of the IP addressing scheme. Second, the script will run without it, but the range of IP addresses that it tests won’t be the correct one.

If the character in the DotTest variable is a period, then execution of the script proceeds after the Else command, and line 21 displays an input dialog box and prompts you for the number that makes up the first node number in the test range. That value is then assigned to the FirstNodeNum variable. Line 22 tests to see whether you indeed typed any characters in the input dialog box or clicked the Cancel button. If you clicked the Cancel button, the Quit method terminates the script. Line 23 then displays another input dialog box and prompts you for the number that makes up the last node number in the test range. That value is then assigned to the LastNodeNum variable. Again, if you clicked the Cancel button, the Quit method terminates the script.

Displaying a progress indicator
Once the End If command terminates the If…Then…Else statement, I use the Popup method in line 26 to display a progress indicator and ask the user to wait. This dialog box is displayed on the screen for one second and then closes itself in order for the script to continue processing the remaining commands.

Preparing the text file
Lines 27 through 31 prepare the text file that will contain the report of the ping command results. The script can create a new report file or append information from the current session to an existing report file. To do this, I’ve used an If…Then…Else statement.

In line 27, I use the FileExists method to determine whether a previous report file exists on the hard drive. If the file is found, the script will use the OpenTextFile method to open the existing file in append mode via the ForAppending constant. I then use the Set command to assign that information to the TheFile variable. If a previous report file doesn’t exist, line 30 will basically use the OpenTextFile method to create a new file and use the Set command to assign that information to the TheFile object variable.

Creating the report header
In lines 32 through 39, I create a report header that contains information about the current session. To do so, I use the TheFile object variable and the WriteBlankLines and WriteLine methods. As you can imagine, the WriteBlankLines method is equivalent to pressing [Enter] to create a blank line, which will then separate the header from the rest of the text in the report. The WriteLine method will then add the text that follows it to the report file.

In line 35, I use the TheDate and the TheTime variables to add the current date and time to the header in order to tell you exactly when the report was generated. In line 36, I combine the NetworkNum with the FirstNodeNum and LastNodeNum variables to add the IP addresses that are being tested in the current session to the header. Then, in line 39, I use the Close method to save the file to disk and close it.

Running the ping command
Now, lines 40 through 44 form the real meat of the script. Here, I use an iterative For…Next loop statement to basically ping every IP address from FirstNodeNum to LastNodeNum. Line 40 takes care of sequentially assigning each node number in the range of IP addresses to the NodeNum variable.

In line 41, I use the Run method of the WshShell object to shell out to DOS via the Cmd.exe /c command.
Cmd.exe is the command interpreter for Windows NT and Windows 2000. If you plan on running this script from Windows 95 or Windows 98, simply replace Cmd.exe with Command.com. Here, Cmd.exe starts a DOS session and the /c parameter configures the command interpreter to carry out the commands that follow it and then exit. In this case, the command that follows it is a ping command.
The ping command pings the IP address created by combining the numbers in the NetworkNum and NodeNum variables. I then use the DOS-based redirection symbols (>>) to pipe the results of the ping command into the report file. To reduce the amount of output the ping command generates, I used the -n 2 parameter to configure the ping command to ping each address twice rather than the default of four times.

I use the DOS-based Echo command and the redirection symbols (>>) to delineate the results of the ping command, formatting the report to make it easier to read. Line 42 runs the Echo. (period) command, which creates a blank line. Line 43 uses another Echo command to add a line of asterisks (*) to the report, which separates the results of each ping command. The Next command then starts the entire operation over again with the next IP address in the specified range.

Displaying the report
Once the For…Next loop statement completes its task of running the ping command, I use the Run method of the WshShell object in line 45 to launch Notepad and open the report file. As soon as that occurs, line 46 runs the Windows Script Host Quit method, which terminates the script.

Using the Ping Automation Tool
Now that you have a good idea of how the Ping Automation Tool script works, let’s take a look at how you would use it. To do so, let’s return to the example I set up earlier, where the systems on your network are statically assigned Class C IP addresses and you’ve lost track of which IP addresses are in use and which are available. Let’s further suppose that the range of Class C IP addresses that you’re using runs from 192.168.0.1 to 192.168.0.50. You need to test all the addresses in this range.

To begin, locate the PingAutomationTool.vbs script file and double-click on it. When you do, you’ll see the Ping Automation Tool dialog box, which prompts you to enter the first three octets of the IP addresses that you want to test. It also reminds you that you need to include a period character after the last number. For our example test, you’d enter 192.168.0. in the text box, as shown in Figure A.

Figure A
When you enter the first three octets of the IP addresses you want to test, be sure to include the period character after the last number.


If you forget to include the period character after the last number, you’ll see the error dialog box shown in Figure B. You’ll then have to start the Ping Automation Tool again.

Figure B
If you don’t type a period character after the last number, the Ping Automation Tool script can’t run correctly and displays this error message.


Once you enter the first three octets of the IP address and click OK, you’ll be prompted to enter the first node number in the range that you want to test. To continue with our example, you’d type 1 in the text box, as shown in Figure C.

Figure C
Next, the script prompts you to enter the first node number in the range that you want to test.


Once you enter the first node number and click OK, you’ll see another dialog box, which will prompt you to enter the last node number in the range that you want to test. To continue with our example, you’d type 50 in the text box, as shown in Figure D.

Figure D
The script then prompts you to enter the last node number in the range you want to test.


After you enter the last node number and click OK, you’ll see the progress dialog box, shown in Figure E, which alerts you that the Ping Automation Tool has begun its job. This dialog box will only appear on the screen for one second and will then close itself so that the script can continue processing.

Figure E
When the Ping Automation Tool begins building the report, you’ll see this dialog box for a moment.


As the script goes to work, you’ll see a command prompt or MS-DOS Prompt button, depending on which operating system you’re running the script in, appear on the taskbar and begin to flash. This is the result of the script shelling out to DOS to run the ping command.

When the operation is finished, Notepad will launch and display the report, as shown in Figure F. As you can see, the header provides you with a nice synopsis of the operation. You’ll also notice that the rest of the report is nicely configured, making it easy to track down the information you want.

Figure F
The Ping Automation Tool displays the results of the ping commands in an easy-to-read report.


Caveats
If you’re running this script from within Windows 95 or Windows 98 and you’re testing a large range of IP addresses, you need to keep in mind that the version of Notepad that comes with these operating systems cannot open text files that are larger than 64 KB. The report file generated for my example test in which I pinged 49 addresses was only 17 KB, so you have some room to work with. However, if you want, you can change the line that loads the Notepad.exe so that it launches another text editor, such as Wordpad.exe. Remember that using another editor may alter the report’s formatting.

Another thing to keep in mind is that this operation can take a long time to complete depending on the size of the range of IP addresses, how powerful the system you’re running it on is, and how much network traffic you encounter. In the case of my example, where I pinged 49 addresses, the operation took a little over two minutes to complete on a 1-GHz system with 256 MB of RAM.

Conclusion
The ping command is a very useful network-debugging tool for quickly troubleshooting TCP/IP connectivity problems. However, since you must run the command from a DOS-based environment, using it can be cumbersome—especially if you need to test a wide range of IP addresses. In this Daily Drill Down, I’ve shown you how to use Windows Script Host and VBScript to create a tool that allows you to automate testing a range of IP addresses. The tool even compiles the results in a nicely formatted, easy-to-read report.
For more information on Windows Scripting Host, read these TechProGuild Daily Drill Downs by Greg Shultz:The authors and editors have taken care in preparation of the content contained herein but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for any damages. Always have a verified backup before making any changes.

About

Greg Shultz is a freelance Technical Writer. Previously, he has worked as Documentation Specialist in the software industry, a Technical Support Specialist in educational industry, and a Technical Journalist in the computer publishing industry.

0 comments