Automating TCP/IP Networking on Clients
Overview
Published: September 1, 2004
By Peter Costantini, the Microsoft Scripting...
A special thanks for their valuable comments and suggestions to:
Ross Carter
Joseph Davies
Steve Lee
Scott McNairy
David M...
Automating TCP/IP Networking on Clients
Part 1: Introduction
Published: July 19, 2004

Looking down from the CIO's office,...
Windows Internet Name Service (WINS). Each section provides detailed explanations and script
examples, with relevant comma...
WMI Class

Notes

41 methods for
Win32_NetworkAdapter

Properties

settings discussed in this paper.

properties;

TCP/IP ...
The related subjects of scripting domain administration and directory services are also not covered in
this paper. However...
can dissect, analyze, and recombine these samples to create scripts that meet your own needs. These
scripts are not design...
are hard-coded into variables near the top of the script. To run these scripts on your computer or
network, you must first...
Windows provides extensive GUI and command-line functionality to help network administrators
manage TCP/IP network clients...
Figure 1

Internet Protocol (TCP/IP) Properties Dialog Box

See full-sized image

The DNS, WINS, and Options tabs also dis...
methods that can retrieve and modify client network settings, the most important of which is the
Win32_NetworkAdapterConfi...
InstancesOf method.
3.

This returns a collection consisting of all the network adapter configurations on the computer.
Fo...
3.

For each network adapter configuration in the collection, use the WSH Echo method to display

the caption "DHCP Enable...
more than one is installed. Index is the key property for the Win32_NetworkAdapterConfiguration
class, serving as the uniq...
Scripting Steps
1.
2.

Connect to the WMI service.
Retrieve a specific instance of the Win32_NetworkAdapterConfiguration c...
property is True.
This returns a collection consisting of the network adapter configurations on the computer for
3.

which...
property is True.
This returns a collection consisting of the network adapter configurations on the computer for
3.

which...
gateway metrics.
Scripting Steps
1.
2.

Create a variable to specify the computer name.
Use a GetObject call to connect to...
1 On Error Resume Next
2
3 strComputer = "."
4 Set objWMIService = GetObject("winmgmts:" _
5

& "{impersonationLevel=imper...
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:scripts...
Ipconfig.exe also uses this information to describe the network adapter.

Figure 4

Relationship Between These WMI Classes...
1 On Error Resume Next
2
3 strComputer = "."
4 Set objWMIService = GetObject("winmgmts:" _
5

& "{impersonationLevel=imper...
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:scripts...
Maximum Speed:
Network Adapter (Device ID)3
Index: 3
MAC Address:
Adapter Type:
Adapter Type Id:
Description: WAN Miniport...
Adapter Type: Ethernet 802.3
Adapter Type Id: 0
Description: Packet Scheduler Miniport
Manufacturer: Microsoft
Name: Packe...
the arp -a command.

Figure 5

Arp.exe output

See full-sized image

To use WMI to connect MAC and IP addresses with netwo...
This returns a collection consisting of all the network adapter configurations on the computer
4.

for which IP is enabled...
1 On Error Resume Next
2
3 strComputer = "."
4 Set objWMIService = GetObject("winmgmts:" _
5

& "{impersonationLevel=imper...
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:scripts...
Figure 6

Correlating Data by Using Win32_NetworkAdapterSetting

See full-sized image

Associating the Network Connections...
Set objWMIService = GetObject("winmgmts:" & strComputer)
In the preceding example, WMI connects to the local computer. The...
string, which occurs only if the computer has responded to the ping.
Note
The ping succeeds only if the routing infrastruc...
1 On Error Resume Next
2
3 strTarget = "192.168.0.1" 'IP address or hostname
4 Set objShell = CreateObject("WScript.Shell"...
perform the same steps performed on the remote computer in the previous example, Ping.vbs.
Listing 15 Ping-multi.vbs
1 On ...
192.168.0.12 responded to ping.
Host Name: client2
192.168.0.13 did not respond to ping.

Pinging a Single Network Host by...
The Win32_PingStatus is unusual within WMI in that you do not call a method to perform
actions with it. Rather, you simply...
1 On Error Resume Next
2
3 strComputer = "."
4 strTarget = " client1" 'IP address or hostname
5 Set objWMIService = GetObj...
When you use Cscript.exe to run this script, output similar to the
following is displayed in the command window: Automatin...
into a long string and display the string with WScript.Echo.
Listing 19 Dhcpsettings.vbs
1 On Error Resume Next
2
3 strComputer = "."
4
5 Set objWMIService = GetObject("winmgmts:" _
6

& "{impersonationLevel=imp...
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:scripts...
8.

If DHCP is already enabled, display a message to that effect with the IP address of the
DHCP server.
Listing 20

Dhcp-...
C:scriptsnetcli>dhcp-enable.vbs
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - ...
note the settings involved before running it.
Listing 21 first displays DHCP settings for each network adapter. It then ch...
1 On Error Resume Next
2
3 strComputer = "."
4 Set objWMIService = GetObject("winmgmts:" _
5

& "{impersonationLevel=imper...
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:scripts...
This returns a collection consisting of all the network adapter configurations on the
3.
4.
5.
6.

computer for which IP i...
1 On Error Resume Next
2
3 strComputer = "."
4 Set objWMIService = GetObject("winmgmts:" _
5

& "{impersonationLevel=imper...
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:scripts...
assigned a default gateway and DNS server before it can reestablish network connectivity. The
script in the next section, ...
changes will take effect.
Listing 23 Staticip-enable.vbs
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Automating tcp
Upcoming SlideShare
Loading in …5
×

Automating tcp

1,123 views

Published on

Windows Scripts for functions network

Published in: Sports, Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,123
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Automating tcp

  1. 1. Automating TCP/IP Networking on Clients Overview Published: September 1, 2004 By Peter Costantini, the Microsoft Scripting Guys Windows scripting technologies enable system administrators to automate many common tasks involved in managing TCP/IP network clients. This paper discusses scripting techniques and shows scripting examples for: • Retrieving TCP/IP client settings. • Working with remote hosts. • Configuring DHCP and static IP addresses. • Managing DNS client settings. • Working with NetBIOS and WINS. Also included are scenarios that combine basic techniques to create sample solutions for more complex networking tasks. • • • • • • • • • • Part 1: Introduction Introduces the scope and organization of the paper, assumptions about technical level of readers, information on how to use the example scripts, and system requirements. Part 2: Scripting Basic TCP/IP Networking on Clients Compares using the Windows graphical user interface, command-line tools, and scripting to retrieve and display TCP/IP client data. Part 3: Scripting Remote Network Management Illustrates scripting techniques for working with TCP/IP settings on multiple remote clients with WMI. Part 4: Scripting IP Address Allocation on Clients Illustrates how to manage DHCP and static IP address settings on clients with scripting. Part 5: Scripting DNS on Clients Illustrates how to manage DNS settings on clients with scripting. Part 6: Scripting WINS on Clients Illustrates how to manage NetBIOS and WINS settings on clients with scripting. Part 7: Scripting Other Network Protocols Illustrates how to manage TCP/IP filtering, other TCP/IP settings, IPX, and network protocols on clients with scripting. Part 8: Using Advanced Scripting Techniques to Manage Networks Illustrates how to use advanced scripting techniques on clients to manage time settings and change other TCP/IP settings in the registry. Part 9: Scenario for Adding New ClientsAnalyzes a script that can add, remove and change network clients and their TCP/IP settings. Part 10: Resources for Scripting Network Management Describes useful books and Internet resources for scripting TCP/IP settings on network clients. Acknowledgements I would like to thank the following people for their contributions and support: My fellow Scripting Guys: Greg Stemp, Dean Tsaltas, Bob Wells, Ethan Wilansky, and Mary Gray Writing Manager: David Mills Publishing Team: Chris Blanton, Jody Ivy, Jon Billow, and Kim McGhee Testing: Richard Min and Larry Petersen Content Testing: Bob Thingwold and Richard Rice
  2. 2. A special thanks for their valuable comments and suggestions to: Ross Carter Joseph Davies Steve Lee Scott McNairy David Meyer Michael Murgolo Mike Poulson David Powell Ben Shy Levi Stevens Don Marshall, Attachmate Corporation Randy Brown, Attachmate Corporation Bill Duncan, Attachmate Corporation Steve Cathersall, Vulcan, Inc. J.C. Warren, Vulcan, Inc. Greg Katsel, Vulcan, Inc
  3. 3. Automating TCP/IP Networking on Clients Part 1: Introduction Published: July 19, 2004 Looking down from the CIO's office, networks based on Transmission Control Protocol/Internet Protocol (TCP/IP) are the nervous systems of many organizations. Their healthy functioning is critical to corporate communications, customer satisfaction, employee morale, and the bottom line. Because of the scale and complexity of such networks and the accessibility of the TCP/IP protocol stack to scripting, the tasks involved in configuring and maintaining TCP/IP networking components are often good candidates for automation. Looking up from the administrative trenches, the work of managing a TCP/IP network sometimes seems to consist of hours of drudgery interrupted by moments of frantic damage control. This paper primarily discusses ways to make those uneventful hours pass in a more reliable, structured, and productive way, which should help reduce the incidence of crises in the bargain. By scripting administrative operations, you can relieve the boredom of repetitious tasks and free more time to deal with less routine issues. Replacing manual procedures, which run the risk of operator error or forgetfulness, with automated maintenance can also alleviate the risk of attacks by malicious viruses and worms and of hardware failures. Scheduling your scripts to run during off-peak hours and without administrator intervention can relieve network traffic jams and reduce user inconvenience. Overall, a well-designed ensemble of scripts, in concert with appropriate Microsoft® Windows® graphical user interface (GUI) and command-line tools, can standardize and systematize network operations, increasing productivity, reliability, and morale. As with most useful things, the kind of scripting discussed in this paper has associated costs. The language, Microsoft® Visual Basic® Scripting Edition (VBScript); the scripting environment, Microsoft® Windows® Script Host (WSH); and the automation library, Windows Management Instrumentation (WMI), typically involve more study to master than the GUI or command-line tools. Nevertheless, although scripting is a form of programming, it is one that does not require four years of computer science study to become proficient and productive. Thousands of system administrators and engineers around the world have learned scripting, used it to great advantage, extended it, and now constitute a community that offers Web sites, newsgroups, and other invaluable resources for those who want to profit from their experience. On This Page Scope and Organization of This Paper Running the Sample Scripts System Requirements Other Important Resources Scope and Organization of This Paper The Windows operating system family provides a variety of tools for managing TCP/IP networks. This paper focuses on the tools that enable you to automate tasks on TCP/IP clients. It covers scripting tools and techniques that enable you to work with the client side of most important elements of TCP/IP networking, including Dynamic Host Configuration Protocol (DHCP), Domain Name System (DNS), and
  4. 4. Windows Internet Name Service (WINS). Each section provides detailed explanations and script examples, with relevant command-line tools and registry keys listed in tables at the end. Beginning with basic scripting techniques, this paper shows increasingly complex variations that open up new functionality. In some areas, it discusses common practical scenarios that require combining different scripting approaches. Its aim, however, is not to show cool scripting tricks for their own sake, but rather to provide flexible ways to automate real-world networking tasks that commonly confront system administrators. This paper covers the following topics: • Scripting basic TCP/IP networking on clients, including comparisons of GUI and command-line tools • • • • • • Extending these scripting techniques to remote and multiple computers. • • to analogous scripting techniques. Scripting IP address allocation with DHCP and static IP addresses. Scripting DNS client management. Scripting WINS client management. Scripting TCP/IP filtering, Internetwork Packet Exchange (IPX), and other network protocols. Advanced scripting techniques that include managing system time and scripting network settings in the registry. A final scenario that combines many previously illustrated techniques in a complex script that adds new clients to a network. A list of important resources that can help you in scripting network clients. Use of VBScript, WSH, and WMI in Scripting Examples Because VBScript is the most popular language for automating Windows administration, all script examples in this paper are written in this language. If you prefer to work in Microsoft JScript®, Perl, or another scripting language, the translation in most cases is simple, because similar techniques apply. These scripts all run under Windows Script Host, the Windows administrative scripting environment; so you can use any language for which a WSH scripting engine is available. VBScript and WSH, however, provide only the language and environment for scripting. Most of the functionality for retrieving configuration information and making changes is included in WMI, which provides hundreds of classes that allow you to work with hardware and software. This paper focuses on just a few WMI classes — ones that include nearly all the TCP/IP client functionality in WMI. The most important class is Win32_NetworkAdapterConfiguration, which contains most of the settings that this paper discusses. Instances of Win32_NetworkAdapterConfiguration have a one-to-one relationship to instances of Win32_NetworkAdapter; in other words, each object representing the configuration settings for a network adapter has a corresponding object representing the hardware of that network adapter. Win32_NetworkAdapterSetting, an association class, represents the relationship between the previous two classes. Win32_NetworkAdapterConfiguration includes 61 read-only properties and 41 methods for changing the properties; Win32_NetworkAdapter and Win32_NetworkAdapterSetting, on the other hand, contain only read-only properties. Table 1 highlights these important classes as well as a few additional classes that contain varying numbers of read-only properties. Among them, only Win32_ComputerSystem and Win32_OperatingSystem contain methods and a few read/write properties. Table 1 WMI Classes That Provide TCP/IP Client Functionality WMI Class Properties Notes Win32_NetworkAdapterConfiguration 61 read-only The most important class for scripting
  5. 5. WMI Class Notes 41 methods for Win32_NetworkAdapter Properties settings discussed in this paper. properties; TCP/IP tasks. Contains most of the changing properties Read-only properties Has a one-to one relationship with instances of Win32_NetworkAdapterSetting Win32_NetworkAdapterConfiguration Read-only properties An association class that represents the relationship between the Win32_NetworkAdapterConfiguration Win32_NetworkProtocol Win32_ComputerSystem Read-only properties Some read-only and a and Win32_NetworkAdapter classes. few read/write properties; Win32_OperatingSystem some methods Some read-only and a few read/write properties; Win32_PingStatus Win32_LocalTime Win32_UTCTime Win32_TimeZone some methods Read-only properties Read-only properties Read-only properties Read-only properties Although the names of the WMI classes Win32_NetworkClient, Win32_NetworkConnection, and Win32_NetworkLoginProfile suggest a relationship to topics in this paper, these classes are not directly relevant to our subject matter. Win32_NetworkConnection, for example, retrieves settings relating to shared network resources currently connected to the computer — not the kind of network connections managed by Network and Dial-up Connections. This paper provides many but not all details about selected WMI classes. For more detailed information about WMI classes, including a more complete list of classes, see the WMI SDK on the Microsoft Developers Network (MSDN) at http://go.microsoft.com/fwlink/?LinkId=24766. Technical Level of This Paper This paper is intended for system and network administrators, engineers, and architects who use or want to use scripting in their work. It assumes some familiarity with scripting and a basic level of networking knowledge. Although it does not try to teach basic scripting or networking, it does explain scripting techniques in detail as they are used. What This Paper Does Not Cover This paper does not cover basic scripting or basic TCP/IP networking. To learn basic system administration scripting techniques, see the Microsoft® Windows® 2000 Scripting Guide and the many example scripts on the TechNet Script Center at http://go.microsoft.com/fwlink/?LinkId=24771. For information about TCP/IP networking on Windows, see Microsoft® Windows Server™ Help, which is included with your Windows Server operating system, and the Microsoft® Windows 2000 Server Resource Kit. The scope of this paper is restricted to scripting TCP/IP clients. Scripting DHCP, DNS, and WINS servers, routers, and network monitoring are not covered.
  6. 6. The related subjects of scripting domain administration and directory services are also not covered in this paper. However, you can find some content relevant to these topics in the Windows 2000 Scripting Guide and also in the example scripts on the TechNet Script Center at http://go.microsoft.com/fwlink/?LinkId=24771. Note This paper covers only scripting for IPv4 networks; it does not provide script examples for IPv6 networks. Command-Line Tools and Batch Files Because this paper focuses on scripting WMI with VBScript and WSH, it does not describe how to use the command-line tools included with the Windows operating system or the Windows 2000 Resource Kit; nor does it cover how to write batch files. Those topics are covered in the documentation for those products and in many other books. At the end of each section, however, a tools section lists the relevant command-line tools. Organization of Scripts The sample scripts in this paper follow some general patterns: Constants and variables In most cases, constants and some variables (usually ones that you want to change) are initialized at the beginning of the script. However, not all variables are initialized before they are used. Almost no variables are declared because VBScript does not require it, which helps keep the scripts shorter. As a debugging aid when writing your own scripts, you may want to explicitly declare all variables with the Dim statement and verify this with the Option Explicit statement. Connecting to the WMI service Nearly all scripts begin by connecting the WMI service and then getting a reference to instances of one or more WMI classes. Linear execution path Most scripts follow a relatively linear execution path to make them simpler and easier to follow. Only a few of the longer and more complex scripts are broken down into subroutines and functions. In some situations, a modular approach may be more adaptable and flexible. If you think you will use a section of code more than once or if you might call it from different places in the script, consider transforming that section of code into a subroutine or function that you can reuse in other scripts. For IT groups where more than one person writes or uses scripts, standardizing scripting formats and conventions can help to reduce confusion and improve code consistency. VBScript error handling Scripts that make changes or that connect to remote computers use the VBScript On Error Resume Next statement along with simple forms of error handling. On Error Resume Next masks errors in the script by allowing the script to continue execution after the line on which the error occurred. When debugging, it can be helpful to temporarily comment out the On Error Resume Next statement by putting a single quotation mark (') at the beginning of the line. Commenting out this statement causes any errors to result in termination of the script with an error message, which can help you locate problems. Most such scripts check to see if the computer is available on the network. If it is, they also check to see if they can connect to the WMI service on that computer because clients with older versions of the operating system might not have WMI installed. You may want to add more robust error handling in other areas where you expect to encounter frequent run-time errors. Sample scripts are code examples, not tools The sample scripts in this paper are offered as code examples that focus on one or a few tasks. You
  7. 7. can dissect, analyze, and recombine these samples to create scripts that meet your own needs. These scripts are not designed as complete, robust tools capable of accomplishing many different tasks and handling many contingencies. An implicit assumption behind the scripts is that they will be run by administrators with some knowledge of scripting, who are capable of editing scripts to change parameters, where necessary. With few exceptions, the scripts do not accept command-line arguments, as many of the more complex scripts included with Windows do, and they do not try to handle all contingencies or possible errors. Caution Sample scripts are not designed to be run as is or by non-scripting support personnel or end users. Top of page Running the Sample Scripts To run any of the sample scripts contained in this paper, follow these steps: 1. 2. 3. Log on with required administrative credentials. Copy the script code to a text file Save it with a .vbs extension. Important Do not copy the line numbers that appear in the left margin (along the left side of most sample scripts). 4. Open a command prompt and navigate to the folder where the script is located. In this paper, the script is always assumed to be in C:Scripts; however, you can place the script in any folder. When you set up your scripting environment, it is recommended that you set the WSH default script host to Cscript.exe, the command-line version, because all these scripts are designed to run at the command prompt. How to do this is explained below. Important If you use Wscript.exe, which is the GUI scripting host, each piece of script output will open a popup that you must then close. This can be time-consuming when a script produces a lot of output and prevents scripts from running unattended. If you are running a script that makes changes, be sure to save your current settings before making changes. How to do this is explained below. Running Scripts with Administrative Credentials Windows, WSH, and WMI security require that you use local Administrator credentials to run scripts on local or remote computers not joined to a domain. On computers joined to a domain, you can also use domain administrator credentials. You cannot do anything with a script that is run under your credentials that you could not do with a command-line tool or in the Windows interface. For more information about security requirements for scripting, see “Tales from the Script – September 2003: Transform Your Workstation into a Scripting Dynamo” on Microsoft TechNet at http://go.microsoft.com/fwlink/?LinkId=24767. Setting the Default Script Host to Cscript To set the default script host to Cscript, suppress the logo (a couple of lines of unnecessary output), and save these settings as the default, run the following at a command prompt: cscript //h:cscript //nologo //s Most of the sample scripts in this paper run against the local computer, which is represented to WMI by the dot or period character (.). In some scripts, values such as computer names or IP addresses
  8. 8. are hard-coded into variables near the top of the script. To run these scripts on your computer or network, you must first change these values to match your network and host configurations. These required changes are explained along with each script. Saving Current Settings Before Running Scripts That Make Changes Some sample scripts make changes on the computer against which they are run. These scripts are flagged with a caution like the one that follows. Caution This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it. Before running a script that makes changes, it is a good idea to save all current IP settings in a text file. You can do this by running the following command line: ipconfig.exe /all > ipconfig.txt This command line redirects the output of ipconfig into a text file in the same folder from which you have run the command. In addition to the ipconfig command, some sections of this paper begin with a script that displays the settings for that networking area. You can use Ipsettings.vbs, Dhcpsettings.vbs, Dnssettings.vbs, and Winssettings.vbs to capture configurations for these areas before running a script that may change them. Top of page System Requirements This paper assumes you are running the scripts on Windows 2000, Windows XP, or Windows Server 2003. Most of the WMI functionality discussed here is available on Windows 2000. However, Windows XP and Windows Server 2003 do include a number of useful new classes, properties, and methods, some of which are illustrated here. System requirements more stringent than the previous will be noted in each section. Whenever possible, run the most recent versions of WSH and VBScript, version 5.6 build 8515, both of which are included in the Windows Script download on MSDN at http://go.microsoft.com/fwlink/? LinkId=27639. This download is available for Microsoft® Windows XP, Windows® 2000, Windows® Millennium Edition (Me), Windows NT® Server 4.0, and Windows® 98. The versions of WMI and Active Directory Service Interfaces (ADSI) depend on the operating system that a computer is running. Microsoft® Windows® Millennium Edition and later versions of the operating system all include WMI. For Windows NT Server 4.0 and Windows 98, you can download WMI version 1.5 from MSDN. For Windows NT Server 4.0 and Windows 98, you can download Active Directory Client Extensions, which allow these operating systems to function as Active D Automating TCP/IP Networking on Clients Part 2: Scripting Basic TCP/IP Networking on Clients Published: July 19, 2004 In some kinds of IT environments, such as convention centers, hotels, and universities, network administrators must frequently change network client information because transient users and computers come and go. In these kinds of computing environments, using scripts to configure network clients may prove particularly useful. Even on less turbulent TCP/IP networks, scripting basic configuration on clients can help standardize change and configuration management, avoid manual administrative errors, and accomplish bulk changes on many clients rapidly and effectively.
  9. 9. Windows provides extensive GUI and command-line functionality to help network administrators manage TCP/IP network clients. Through Network and Dial-Up Connections in Windows 2000 and Network Connections in Windows XP and Windows Server 2003 (in Control Panel), you can view and modify most network settings. Widely used command-line tools such as Ipconfig.exe and Ping.exe provide additional options. Sometimes these are all you need to accomplish a networking task. However, if you find yourself clicking OK repeatedly or trying to change a parameter that is contingent on the state of two other parameters on a hundred computers, the techniques detailed in this paper should prove useful. This section covers the basic techniques for retrieving and changing the most common TCP/IP settings, such as IP addresses and subnet masks. The section begins with a brief review of the non-scripting methods and command-line methods that you can use to perform these tasks. Next, the section covers a variety of scripting techniques for working with the two most important WMI classes for these tasks. Finally, it shows how to retrieve extended TCP/IP settings by using a script that reproduces nearly all the functionality of the ipconfig /all command. On This Page Retrieving Basic TCP/IP Client Settings by Using Non-Scripting Methods Retrieving Basic Settings with a Script Displaying Expanded IP Configuration Data Tools for Basic TCP/IP Networking on Clients Retrieving Basic TCP/IP Client Settings by Using Non-Scripting Methods To simply check a couple of TCP/IP settings on one computer, many network administrators prefer to use the Windows interface that is provided in Windows XP through Network Connections and in Windows 2000 through Network and Dial-Up Connections. To check TCP/IP settings by using the Windows interface in Windows XP 1. 2. Open Control Panel and double-click Network Connections. In the Network Connections dialog box, right-click a specific network connection and then 3. click Properties. In the properties dialog box for the network connection, select Internet Protocol (TCP/IP) and then click Properties. Figure 1 shows the available options when you use the Internet Protocol (TCP/IP) Properties dialog box.
  10. 10. Figure 1 Internet Protocol (TCP/IP) Properties Dialog Box See full-sized image The DNS, WINS, and Options tabs also display settings for those technologies and enable you to change most settings. Getting Basic Settings by Using Ipconfig.exe Many administrators use command-line tools to obtain TCP/IP client configuration information. One popular command-line tool is Ipconfig.exe, which is included with the Windows operating system. Figure 2 illustrates the network settings you can display by using Ipconfig.exe. Figure 2 Typical Network Settings Displayed by Ipconfig.exe See full-sized image You can use this tool not only to display networking settings but also to perform certain operations. For example, the /renew option renews DHCP leases and the /flushdns option purges the DNS client resolver cache. Top of page Retrieving Basic Settings with a Script By writing scripts in VBScript that use WSH and WMI, system administrators can create more powerful and flexible tools to manage a broader range of Windows functionality. For each setting in the Advanced TCP/IP Settings dialog box, WMI classes offer properties and
  11. 11. methods that can retrieve and modify client network settings, the most important of which is the Win32_NetworkAdapterConfiguration class. Figure 3 illustrates which WMI classes correspond to different elements of the Advanced TCP/IP Settings dialog box. Figure 3 How TCP/IP WMI Properties and Methods Correspond to the Windows UI See full-sized image For purposes of scripting, a WMI class is simply a way of packaging a related set of configuration settings and configuring them into a bundle with a recognizable name. Scripts call the properties to retrieve the settings and methods in order to change them. Win32_NetworkAdapterConfiguration also includes properties and methods that correspond to the DNS, WMI, and Options tabs of the Advanced TCP/IP Settings dialog box. The sections that follow cover this in detail. Using the Win32_NetworkAdapterConfiguration WMI Class The 61 properties and 41 methods of Win32_NetworkAdapterConfiguration cover nearly all the settings and actions that are available through the Windows interface or command-line tools, and some that are not. To retrieve a property or call a method, only a few lines of VBScript code are required, as the following examples illustrate. For more information about the properties and methods for this WMI class, see the WMI Software Development Kit (SDK) topic at http://go.microsoft.com/fwlink/? LinkId=29991. Calling the InstancesOf() or ExecQuery() methods of the SWbemServices object on Win32_NetworkAdapterConfiguration returns a collection of objects. This collection is in the form of an SWbemObjectSet collection containing zero or more SWbemObject instances. These objects and methods are documented in detail in the WMI Reference of the WMI SDK under "Scripting API for WMI." Displaying One Setting The following example displays the DHCPEnabled property of Win32_NetworkAdapterConfiguration. The DHCPEnabled property returns a Boolean value, which is a way of representing a condition that can be either true or false. The values used by VBScript are -1 for true and 0 for false; however, any non-zero value can be used programmatically to represent true. In most cases, scripts should use True and False, which are the two VBScript keywords, to represent these values. The pattern used in this simple script can be repeated for any property of Win32_NetworkAdapterConfiguration except for those that return arrays. Handling properties that return arrays is discussed later in this paper. Scripting Steps 1. 2. Connect to the WMI service using the "winmgmts:" moniker. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the
  12. 12. InstancesOf method. 3. This returns a collection consisting of all the network adapter configurations on the computer. For each network adapter configuration in the collection, use the WSH Echo method to display the Boolean property corresponding to the DHCP Enabled setting in the IP addresses box on the IP Settings tab of the Advanced TCP/IP Settings dialog box. Listing 1 Onesetting.vbs 1 Set objWMIService = GetObject("winmgmts:") 2 Set colNicConfig = _ 3 objWMIService.InstancesOf("Win32_NetworkAdapterConfiguration") 4 For Each objNicConfig In colNicConfig 5 WScript.Echo objNicConfig.DHCPEnabled 6 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>onesetting.vbs -1 0 0 0 0 0 0 0 Note A computer that contains only one physical network adapter may show settings for multiple network adapters. This is because some kinds of network connections, such as virtual private networks (VPNs), create their own virtual network adapters. Displaying a Boolean Setting as a String To produce more readable output, a minor change in line 5 causes the Boolean settings to be displayed as True or False rather than -1 or 0, which increases the readability of the script's output. By echoing "DHCP Enabled: " first and then concatenating the DHCPEnabled property, the script allows VBScript to "coerce" the Boolean setting into a string format. Although all VBScript variables are type variant, VBScript automatically coerces (transforms) variants into appropriate data subtypes depending on the context in which they occur. In this case, because the script concatenates a variable of subtype Boolean onto a literal string, VBScript automatically converts the Boolean to its string equivalent. Scripting Steps 1. Connect to the WMI service. 2. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the InstancesOf method. This returns a collection consisting of all the network adapter configurations on the computer.
  13. 13. 3. For each network adapter configuration in the collection, use the WSH Echo method to display the caption "DHCP Enabled:" concatenated with the Boolean property DHCPEnabled. Listing 2 Onesetting-string.vbs 1 Set objWMIService = GetObject("winmgmts:") 2 Set colNicConfig = _ 3 objWMIService.InstancesOf("Win32_NetworkAdapterConfiguration") 4 For Each objNicConfig In colNicConfig 5 WScript.Echo "DHCP Enabled: " & objNicConfig.DHCPEnabled 6 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>onesetting-string.vbs DHCP Enabled: True DHCP Enabled: False DHCP Enabled: False DHCP Enabled: False DHCP Enabled: False DHCP Enabled: False DHCP Enabled: False DHCP Enabled: False Displaying a Setting for Specific Network Adapters The previous two examples display the value of the DHCPEnabled property for every network adapter configuration that WMI can find. Sometimes you may not want to work with all network adapters. For example, certain features, such as Routing and Remote Access and virtual private networks, may create their own virtual network adapter configurations on which TCP/IP is not enabled. To filter for IP-enabled network adapters only, you can use the ExecQuery() method of the SWbemServices object, the object type returned by the GetObject() call on line 1. As a required parameter, ExecQuery() generally takes a string containing a query in WMI Query Language (WQL), a dialect of Structured Query Language (SQL). It returns an SWbemObjectSet collection of objects. Although WQL queries are not case sensitive, putting all WQL keywords in caps is the standard convention because it makes the script more legible. The most basic query used by system administrative scripts is "SELECT * FROM classname". This query returns all instances of the class, and the "*" serves as a wildcard character (as in SQL and command-line file system specifiers) that returns all the properties of each instance. For example, "SELECT * FROM Win32_Service" would return all the properties of all the instances of the Win32_Service class, which would represent all the services currently running on the computer. In the following script, the WHERE keyword (also part of SQL) enables you to specify limiting conditions for the query. Here the query "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True" requests all instances of the Win32_NetworkAdapterConfiguration class where the Boolean value of its IPEnabled property is True, in other words, for which IP is enabled. This example also adds a second property, Index (see line 5), to distinguish between adapters when
  14. 14. more than one is installed. Index is the key property for the Win32_NetworkAdapterConfiguration class, serving as the unique identifier for each instance of the class. The value of Index is an integer, starting with 0 for the first active network adapter configuration and incrementing by 1 for each successive one, that identifies a particular configuration. Listing 3 returns the Index and DHCPEnabled properties for all adapters for which IPEnabled is True. Scripting Steps 1. 2. Connect to the WMI service. Retrieve specific instances of the Win32_NetworkAdapterConfiguration class with the ExecQuery method and a query string that filters for those network adapters where the IPEnabled property is True. This returns a collection consisting of the network adapter configurations on the computer for 3. which IP is enabled. For each network adapter configuration in the collection, use the WSH Echo method to display the index of the network adapter and the DHCPEnabled property. Listing 3 Onesetting-execquery.vbs 1 Set objWMIService = GetObject("winmgmts:") 2 Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _ 3 "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 4 For Each objNicConfig In colNicConfig 5 WScript.Echo "Network Adapter: " & objNicConfig.Index 6 WScript.Echo " DHCP Enabled: " & objNicConfig.DHCPEnabled 7 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>onesetting-execquery.vbs Network Adapter: 1 DHCP Enabled: True Network Adapter: 10 DHCP Enabled: False In other cases, you may want to restrict the script to running against just a single network adapter configuration. For example, on a dual-homed computer that is connected to two networks, you might want to enable DHCP on one network adapter but not the other. To do this, you could use a WQL query such as "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = 0." A simpler way to accomplish the same thing is to use the Get() method of the SWbemServices object (returned by the GetObject call to the wingmgts: moniker). Get() takes a string containing a WMI object path as a required parameter and returns an SWbemObject object. Tip The following script displays a quirk of WMI: although VBScript, WSH, and WMI typically ignore white space, within the object path (the string parameter) passed to objWMIService.Get() there can be no space before or after the equal sign (=) in "Index=0." A space on either side of the equal sign causes an error.
  15. 15. Scripting Steps 1. 2. Connect to the WMI service. Retrieve a specific instance of the Win32_NetworkAdapterConfiguration class with the Get method and an object path that specifies an Index property (the key property) equal to 0. This returns a collection consisting of the network adapter configuration on the computer for 3. which the index is 0. For this instance, use the WSH Echo method to display the index of the network adapter and the DHCPEnabled property. Listing 4 Onesetting-onenic.vbs 1 intIndex = 1 ' index of an IP-enabled network adapter 2 Set objWMIService = GetObject("winmgmts:") 3 Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _ 4 "Win32_NetworkAdapterConfiguration WHERE Index = " & intIndex) 5 For Each objNicConfig In colNicConfig 6 WScript.Echo "Network Adapter: " & objNicConfig.Index 7 WScript.Echo " DHCP Enabled: " & objNicConfig.DHCPEnabled 8 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>onesetting-onenic.vbs Network Adapter: 1 DHCP Enabled: True Displaying Multi-Valued Properties Because Windows allows a single network adapter setting to have more than one IP address, subnet mask, default gateway, or DNS server, some properties of Win32_NetworkAdapterConfiguration can have multiple values. WMI returns these multiple values in the form of an array. Because an array contains multiple values, it cannot be handled in the same way as a single string, Boolean, or number. VBScript offers two techniques for transforming arrays into a string format that can be displayed with WScript.Echo: the Join function and the For Each loop. Using the VBScript Join function The VBScript Join function concatenates or joins together the elements of an array into a single string that is separated by a character or characters specified in an optional second parameter. If you do not specify this delimiter, Join uses a single space. The Join function is necessary because you cannot directly display an array. First, you must divide the array into its elements or convert the array into a string. Join allows you to control the formatting of this string. For example, you can use either commas or colons (rather than spaces) to separate the elements of the array. Scripting Steps 1. 2. Connect to the WMI service. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the ExecQuery method and a query string that filters for those network adapters where the IPEnabled
  16. 16. property is True. This returns a collection consisting of the network adapter configurations on the computer for 3. which IP is enabled. For each network adapter configuration in the collection, use the WSH Echo method to display 4. the index of the network adapter. If the IPAddress property (an array): • Is not Null, use the VBScript Join function to concatenate the elements of the IPAddress array into a string with elements separated by a space (the default) and assign them to a variable. • Is Null, assign an empty string to the variable. 5. Display the space-delimited string of IP addresses. Listing 5 Onesetting-array-join.vbs 1 Set objWMIService = GetObject("winmgmts:") 2 Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _ 3 "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 4 For Each objNicConfig In colNicConfig 5 WScript.Echo "Network Adapter: " & objNicConfig.Index 6 If Not IsNull(objNicConfig.IPAddress) Then 7 strIPAddresses = Join(objNicConfig.IPAddress) 8 Else 9 strIPAddresses = "" 10 End If 11 WScript.Echo " IP Address(es): " & strIPAddresses 12 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>onesetting-array-join.vbs Network Adapter: 1 IP Address(es): 0.0.0.0 Network Adapter: 10 IP Address(es): 192.168.1.2 Using For Each ... In ... Next The For Each loop provides an alternative way to display the elements of an array. This statement iterates through the array, allowing the script to separately perform an action on each element. In this case, we merely display the element. Scripting Steps 1. 2. Connect to the WMI service. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the ExecQuery method and a query string that filters for those network adapters where the IPEnabled
  17. 17. property is True. This returns a collection consisting of the network adapter configurations on the computer for 3. which IP is enabled. For each network adapter configuration in the collection, use the WSH Echo method to display 4. the index of the network adapter. If the IPAddress property (an array) is not Null, use a For Each loop to iterate through the IPAddress array, displaying each element with the WSH Echo method. Listing 6 Onesetting-array-foreach.vbs 1 Set objWMIService = GetObject("winmgmts:") 2 Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _ 3 "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 4 For Each objNicConfig In colNicConfig 5 WScript.Echo "Network Adapter: " & objNicConfig.Index 6 WScript.Echo " 7 If Not IsNull(objNicConfig.IPAddress) Then 8 IP Address(es):" For Each strIPAddress In objNicConfig.IPAddress 9 WScript.Echo " 10 Next 11 " & strIPAddress End If 12 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>onesetting-array-foreach.vbs Network Adapter: 1 IP Address(es): 0.0.0.0 Network Adapter: 10 IP Address(es): 192.168.1.2 Displaying a Range of Networking Properties When inventorying network clients, you might often want to gather information about a larger selection of TCP/IP settings. For example, you might want to collect the settings displayed in the Advanced TCP/IP Settings dialog box and those shown by Ipconfig.exe. There is overlap between the two but also some differences. A script can combine all the settings from these sources into one package. For each IP-enabled network adapter on a specific computer, use Ipsettings.vbs to obtain the information that displays on the IP Settings tab of the Advanced TCP/IP Settings dialog box for a network connection as well as the information that Ipconfig.exe (used with a few parameters) displays. A network adapter configuration can have multiple IP addresses, subnets, default gateways, and
  18. 18. gateway metrics. Scripting Steps 1. 2. Create a variable to specify the computer name. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation 3. level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.” This returns a collection consisting of all the network adapter configurations on the computer 4. for which IP is enabled. For each network adapter configuration in the collection, use the WSH Echo method to display 5. the properties corresponding to the settings on the IP Settings tab. For those properties that return an array, use the VBScript IsNull() function to check whether the array is null. • If the array is not null, use the VBScript Join() function to concatenate the array elements • If the array is null, display an empty string. Listing 7 into a string and display the string. Ipsettings.vbs
  19. 19. 1 On Error Resume Next 2 3 strComputer = "." 4 Set objWMIService = GetObject("winmgmts:" _ 5 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 6 Set colNicConfigs = objWMIService.ExecQuery _ 7 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 8 9 WScript.Echo VbCrLf & "IP Settings" 10 11 For Each objNicConfig In colNicConfigs 12 13 WScript.Echo VbCrLf & " 14 WScript.Echo " " & objNicConfig.Description & VbCrLf 15 WScript.Echo " DHCP Enabled: 16 17 18 19 20 Network Adapter " & objNicConfig.Index " & _ objNicConfig.DHCPEnabled If Not IsNull(objNicConfig.IPAddress) Then strIPAddresses = Join(objNicConfig.IPAddress) Else strIPAddresses = "" 21 End If 22 WScript.Echo " 23 If Not IsNull(objNicConfig.IPSubnet) Then 24 25 26 IP Address(es): " & strIPAddresses strIPSubnet = Join(objNicConfig.IPSubnet) Else strIPSubnet = "" 27 End If 28 WScript.Echo " 29 If Not IsNull(objNicConfig.DefaultIPGateway) Then 30 31 Subnet Mask(s): " & strIPSubnet strDefaultIPGateway = Join(objNicConfig.DefaultIPGateway) Else
  20. 20. When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>ipsettings.vbs IP Settings Network Adapter 1 Intel(R) PRO/1000 MT Network Connection - Packet Scheduler Miniport DHCP Enabled: True IP Address(es): 0.0.0.0 Subnet Mask(s): Default Gateways(s): Gateway Metric(s): Interface Metric: 1 Connection-specific DNS Suffix: Network Adapter 10 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) - Packet Scheduler Miniport DHCP Enabled: False IP Address(es): 192.168.1.2 Subnet Mask(s): 255.255.255.0 Default Gateways(s): Gateway Metric(s): Interface Metric: 20 Connection-specific DNS Suffix: Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter Win32_NetworkAdapterConfiguration is closely related to Win32_NetworkAdapter, another WMI class. There is a one-to-one correspondence between instances of the two classes and an implicit division of labor between the two classes: Win32_NetworkAdapter exposes mostly hardware-related properties, and in contrast to Win32_NetworkAdapterConfiguration, includes no methods. There is some overlap between the two classes: for example, both have a MACAddress property that retrieves the physical address of a network adapter. Figure 4 illustrates the relationship between the Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter classes. Only Win32_NetworkAdapter, however, has a NetConnectionID property (available only on Windows XP and Windows Server 2003) that returns the name of the Network Connection (from Network Connections) that is bound to the network adapter, even though such a software setting might more logically belong in Win32_NetworkAdapterConfiguration. This NetConnectionID property corresponds to the name that Ipconfig.exe uses for each network adapter. In addition, Win32_NetworkAdapter alone includes an AdapterType property that describes the network medium to which the adapter connects, such as Ethernet 802.3 or Token Ring 802.5.
  21. 21. Ipconfig.exe also uses this information to describe the network adapter. Figure 4 Relationship Between These WMI Classes See full-sized image The following examples show how to display the properties of Win32_NetworkAdapter and also the methods for correlating properties from instances of Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration. Displaying Network Adapter Properties Displaying network adapter settings requires similar scripting techniques to those involved in displaying TCP/IP settings. The only difference is that you use the Win32_NetworkAdapterConfiguration class to display TCP/IP settings and the Win32_NetworkAdapter class to display network adapter properties. For more information about the properties and methods for this WMI class, see the WMI Software Development Kit (SDK) topic at http://go.microsoft.com/fwlink/?LinkId=29992. Scripting Steps Listing 8 retrieves the properties for all the network adapters on a computer. This script retrieves some properties available only on Windows XP and Windows Server 2003. 1. Create a variable to specify the computer name. For example, to specify the local computer, 2. use ("."). Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation 3. level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapter class. 4. 5. This returns a collection consisting of all the network adapters on the computer. For each network adapter in the collection, use the WSH Echo method to display its properties. For those properties that return an array, use the VBScript IsNull() function to check whether the array is null. • If the array is not null, use the VBScript Join() function to concatenate the array elements • If the array is null, display an empty string. Listing 8 into a string and display the string. Nicsettings.vbs
  22. 22. 1 On Error Resume Next 2 3 strComputer = "." 4 Set objWMIService = GetObject("winmgmts:" _ 5 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 6 Set colNics = objWMIService.ExecQuery _ 7 ("SELECT * FROM Win32_NetworkAdapter") 8 9 WScript.Echo VbCrLf & "Network Adapter Settings" 10 11 For Each objNic In colNics 12 13 14 WScript.Echo VbCrLf & " Network Adapter (Device ID)" & _ objNic.DeviceID 15 Wscript.Echo " Index: " & objNic.Index 16 Wscript.Echo " MAC Address: " & objNic.MACAddress 17 Wscript.Echo " Adapter Type: " & objNic.AdapterType 18 Wscript.Echo " Adapter Type Id: " & objNic.AdapterTypeID 19 Wscript.Echo " Description: " & objNic.Description 20 Wscript.Echo " Manufacturer: " & objNic.Manufacturer 21 Wscript.Echo " Name: " & objNic.Name 22 Wscript.Echo " Product Name: " & objNic.ProductName 23 Wscript.Echo " Net Connection ID: " & objNic.NetConnectionID 24 Wscript.Echo " Net Connection Status: " & objNic.NetConnectionStatus 25 Wscript.Echo " PNP Device ID: " & objNic.PNPDeviceID 26 Wscript.Echo " Service Name: " & objNic.ServiceName 27 If Not IsNull(objNic.NetworkAddresses) Then 28 29 30 31 strNetworkAddresses = Join(objNic.NetworkAddresses) Else strNetworkAddresses = "" End If
  23. 23. When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>nicsettings.vbs Network Adapter Settings Network Adapter (Device ID)1 Index: 1 MAC Address: 00:0D:56:15:ED:B7 Adapter Type: Ethernet 802.3 Adapter Type Id: 0 Description: Intel(R) PRO/1000 MT Network Connection Manufacturer: Intel Name: Intel(R) PRO/1000 MT Network Connection Product Name: Intel(R) PRO/1000 MT Network Connection Net Connection ID: Local Area Connection Net Connection Status: 7 PNP Device ID: PCIVEN_8086&DEV_100E&SUBSYS_01511028&REV_024&1C660DD6&0&60F0 Service Name: E1000 NetworkAddresses: Permanent Address: AutoSense: Maximum Number Controlled: 0 Speed: Maximum Speed: Network Adapter (Device ID)2 Index: 2 MAC Address: Adapter Type: Adapter Type Id: Description: RAS Async Adapter Manufacturer: Name: RAS Async Adapter Product Name: RAS Async Adapter Net Connection ID: Net Connection Status: PNP Device ID: Service Name: NetworkAddresses: Permanent Address: AutoSense: Maximum Number Controlled: 0 Speed:
  24. 24. Maximum Speed: Network Adapter (Device ID)3 Index: 3 MAC Address: Adapter Type: Adapter Type Id: Description: WAN Miniport (L2TP) Manufacturer: Microsoft Name: WAN Miniport (L2TP) Product Name: WAN Miniport (L2TP) Net Connection ID: Net Connection Status: PNP Device ID: ROOTMS_L2TPMINIPORT0000 Service Name: Rasl2tp NetworkAddresses: Permanent Address: AutoSense: Maximum Number Controlled: 0 Speed: Maximum Speed: Network Adapter (Device ID)6 Index: 6 MAC Address: Adapter Type: Adapter Type Id: Description: Direct Parallel Manufacturer: Microsoft Name: Direct Parallel Product Name: Direct Parallel Net Connection ID: Net Connection Status: PNP Device ID: ROOTMS_PTIMINIPORT0000 Service Name: Raspti NetworkAddresses: Permanent Address: AutoSense: Maximum Number Controlled: 0 Speed: Maximum Speed: Network Adapter (Device ID)8 Index: 8 MAC Address: 00:0D:56:15:ED:B7
  25. 25. Adapter Type: Ethernet 802.3 Adapter Type Id: 0 Description: Packet Scheduler Miniport Manufacturer: Microsoft Name: Packet Scheduler Miniport Product Name: Packet Scheduler Miniport Net Connection ID: Net Connection Status: PNP Device ID: ROOTMS_PSCHEDMP0000 Service Name: PSched NetworkAddresses: Permanent Address: AutoSense: Maximum Number Controlled: 0 Speed: Maximum Speed: Network Adapter (Device ID)10 Index: 10 MAC Address: 00:0A:5E:3D:E3:70 Adapter Type: Ethernet 802.3 Adapter Type Id: 0 Description: 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) Manufacturer: 3Com Name: 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) Product Name: 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) Net Connection ID: Local Area Connection 2 Net Connection Status: 2 PNP Device ID: PCIVEN_10B7&DEV_9200&SUBSYS_100010B7&REV_784&1C660DD6&0&40F0 Service Name: EL90Xbc NetworkAddresses: Permanent Address: AutoSense: Maximum Number Controlled: 0 Speed: Maximum Speed: Associating the Network Connections Name with MAC and IP Addresses Using Two Classes For various purposes, administrators may need to retrieve the MAC or physical addresses and IP addresses of computers and correlate them with the name of the adapter listed in Network Connections. Ipconfig.exe uses the network adapter name and type to distinguish between network adapters, as shown in Figure 5. Associating MAC and IP addresses corresponds to the part of the IP routing process performed by the Address Resolution Protocol (ARP). You can view the resulting IP - MAC address translation tables by using the command-line tool Arp.exe. Figure 5 provides an example of the output obtained by running
  26. 26. the arp -a command. Figure 5 Arp.exe output See full-sized image To use WMI to connect MAC and IP addresses with network adapter names and types, you must correlate properties from corresponding instances of Win32_NetworkAdapterConfiguration (MACAddress and IPAddress) and Win32_NetworkAdapter (NetConnectionID and AdapterType). The NetConnectionID property of Win32_NetworkAdapter is available only on Windows XP and Windows Server 2003. In order to find the specific instances of each class that correspond to each other, you can use the Key qualifier to determine key properties for each class. Key properties (there can be more than one) together supply a unique reference for each class instance and are part of the instance namespace handle. They are a little like the key field in a database. The WMI SDK or Wbemtest.exe (the WMI Tester tool, which is included on all versions of Windows that include WMI) can tell you which property or properties of a class are keys. Table 2 displays the key properties for the two WMI network adapter classes. Table 2 Key Properties for WMI Network Adapter Classes Class Key Property Win32_NetworkAdapterConfiguration Index Win32_NetworkAdapter DeviceID By using either of these keys, you can match instances of the two classes. In the following example, the Get property of SWbemServices is used to retrieve the instance of Win32_NetworkAdapter, whose DeviceID property corresponds to the Index property of a specific Win32_NetworkAdapterConfiguration instance. Getncmacip.vbs displays the network connection name (or index number for pre-Windows XP clients), MAC address, IP addresses, and subnet masks for IP-enabled network interfaces. A network adapter configuration can have more than one IP address and subnet. The script gets properties from corresponding instances of Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration by using the direct correlation between Win32_NetworkAdapter.DeviceID and Win32_NetworkAdapterConfiguration.Index. The script shows a simpler way than the GetNetConnectionID() function in Ipsettings.vbs to determine whether the NetConnectionID property is available. Instead of checking the operating system version to see if it is Windows XP (which would ensure that the Win32_NetworkAdapter.NetConnectionID was available), it simply tries to retrieve the NetConnectionID property. If an error is returned, it uses the Win32_NetworkAdapterConfiguration.Index property instead. Scripting Steps Listing 9 retrieves the IP addresses and subnet masks for each network adapter on a single computer. 1. 2. Create a variable to specify the computer name. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation 3. level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”
  27. 27. This returns a collection consisting of all the network adapter configurations on the computer 4. for which IP is enabled. Iterate through each network adapter configuration in the collection, performing the following 5. steps. Use the Get method of the objWMIService object to fetch the instance of Win32_NetworkAdapter whose DeviceID property equals the Index property of 6. Win32_NetworkAdapterConfiguration. Display the AdapterType and NetConnectionID properties of the current instance of Win32_NetworkAdapter. If an error occurs, the NetConnectionID property does not exist (this property is new to Windows XP and Windows Server 2003); so switch back to displaying the Index property of 7. Win32_NetworkAdapterConfiguration to identify the current network adapter. Display the Description property of Win32_NetworkAdapterConfiguration and the MACAddress property of Win32_NetworkAdapter. 8. Display the IPAddress and IPSubnet properties of Win32_NetworkAdapterConfiguration. Listing 9 Getncmacip.vbs
  28. 28. 1 On Error Resume Next 2 3 strComputer = "." 4 Set objWMIService = GetObject("winmgmts:" _ 5 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 6 Set colNicConfigs = objWMIService.ExecQuery _ 7 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 8 9 WScript.Echo VbCrLf & "MAC & IP Addresses & Subnet Masks" 10 11 For Each objNicConfig In colNicConfigs 12 13 14 Set objNic = objWMIService.Get _ ("Win32_NetworkAdapter.DeviceID=" & objNicConfig.Index) 15 16 WScript.Echo VbCrLf & " 17 objNic.NetConnectionID 18 If Err Then 19 20 " & objNic.AdapterType & " " & _ WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index End If 21 22 WScript.Echo " " & objNicConfig.Description & VbCrLf 23 WScript.Echo " MAC Address:" & VbCrLf & _ 24 " " & objNic.MACAddress 25 WScript.Echo " 26 For Each strIPAddress In objNicConfig.IPAddress 27 WScript.Echo " IP Address(es):" " & strIPAddress 28 Next 29 WScript.Echo " 30 For Each strIPSubnet In objNicConfig.IPSubnet 31 WScript.Echo " Subnet Mask(s):" " & strIPSubnet
  29. 29. When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>getncmacip.vbs MAC & IP Addresses & Subnet Masks Ethernet 802.3 Local Area Connection Intel(R) PRO/1000 MT Network Connection - Packet Scheduler Miniport MAC Address: 00:0D:56:15:ED:B7 IP Address(es): 0.0.0.0 Subnet Mask(s): Ethernet 802.3 Local Area Connection 2 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) - Packet Scheduler Miniport MAC Address: 00:0A:5E:3D:E3:70 IP Address(es): 192.168.1.2 Subnet Mask(s): 255.255.255.0 Using Association Classes to Retrieve Correlated Data Another way to get data from related instances of Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter is to use the association class, Win32_NetworkAdapterSetting. In this case, the properties to be correlated are the NetConnectionID and MACAddress properties of Win32_NetworkAdapter and the IPAddress and IPSubnet properties of Win32_NetworkAdapterConfiguration. Figure 6 illustrates how the Win32_NetworkAdapterSetting association class is used to obtain data from related instances of these two classes. This example uses an ASSOCIATORS OF query with the ExecQuery method of SWbemServices to associate properties from the two classes. ASSOCIATORS OF is a keyword of WMI Query Language (WQL).
  30. 30. Figure 6 Correlating Data by Using Win32_NetworkAdapterSetting See full-sized image Associating the Network Connections Name with IP Addresses Using an Association Class Getncmacip-assoc.vbs displays the network connection name (called an index number on clients that run an operating system older than Windows XP), MAC address, IP addresses, and subnet masks for IP-enabled network interfaces. It uses the Win32_NetworkAdapterSetting association class to correlate properties from Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter. A network adapter configuration can have more than one IP address and subnet. Scripting Steps Listing 10 retrieves the TCP/IP network client properties on a single computer. 1. 2. Create a variable to specify the computer name. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation 3. level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.” This returns a collection consisting of all the network adapter configurations on the computer 4. for which IP is enabled. For each network adapter configuration in the collection, use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class with an ASSOCIATORS OF query. The query returns a collection of instances of Win32_NetworkAdapter. An ASSOCIATORS OF query uses the Win32_NetworkAdapterSetting association class to correlate the instances of Win32_NetworkAdapterConfiguration (identified by the Index 5. property) with the corresponding instances of the associated class, Win32_NetworkAdapter. Iterate through the collection of instances of Win32_NetworkAdapter, displaying the AdapterType, NetConnectionID, and MACAddress properties. If an error occurs when displaying the NetConnectionID property, display instead the Index of 6. the corresponding instance of Win32_NetworkAdapterConfiguration. Display the IPAddress and IPSubnet properties for the instance of Win32_NetworkAdapterConfiguration associated with the current instance of Win32_NetworkAdapter. Listing 10 Getncmacip-assoc.vbs
  31. 31. Set objWMIService = GetObject("winmgmts:" & strComputer) In the preceding example, WMI connects to the local computer. The period or dot character, (.) represents the local computer in WMI object paths. It connects to the default WMI namespace — typically rootcimv2 — by using the default impersonation level, "impersonate." To connect to WMI on a remote computer, replace "." with the name of the remote computer: strComputer = "client1" Set objWMIService = GetObject("winmgmts:" & strComputer) As on local computers, you must have sufficient administrative privileges on the remote computer to perform the actions that the script takes. For more information about connecting to WMI, see the topic "Connecting to WMI Using the WMI Moniker," which is in the "WMI Scripting Primer" chapter of the Windows 2000 Scripting Guide at http://go.microsoft.com/fwlink/?LinkId=29993. Getting the IP Addresses and Subnet Masks of a Remote Computer The following script shows how to retrieve a couple of TCP/IP client settings from a remote computer. The code is almost identical to the code used in scripts that connect to WMI on the local computer; the only difference is that the name of an accessible remote computer is assigned to the strComputer variable. Scripting Steps Listing 13 retrieves the IPAddress and IPSubnet properties (both arrays) for each network adapter configuration on a remote computer. 1. 2. Invoke On Error Resume Next, which is the error-handling mechanism of VBScript. Create a variable to specify the remote computer name. This code is similar to that used in most scripts in this paper that run locally. However, the script assigns the string “client1” (the name of a remote computer) — in place of "." (the local computer) — to strComputer. To run this script, replace "client1" on line 3 with the name of an accessible remote computer 3. on which you have administrative privileges. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.” Here strComputer is concatenated into the object path so that the script binds to the rootcimv2 namespace on the remote computer. The impersonation level 4. and namespace are specified explicitly. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.” This returns a collection consisting of all the network adapter configurations on the computer 5. for which IP is enabled. For each network adapter configuration in the collection, retrieve the index number, description, IP addresses, and subnet masks. Listing 13 Getip.vbs
  32. 32. string, which occurs only if the computer has responded to the ping. Note The ping succeeds only if the routing infrastructure forwards the ping messages and the destination is not using a firewall that prevents the ping messages from being received. Pinging a Single Network Host by Running Ping.exe from a Script To determine whether a computer is accessible on the network before trying to connect to WMI and perform a task on it, a script can use WSH to call Ping.exe. VBScript provides string-handling functions that enable the script to parse the resulting StdOut stream to see if the remote computer responded and act accordingly. Scripting Steps Listing 14 illustrates how to run Ping.exe with the WshShell Exec() method. 1. 2. Invoke the VBScript error-handling mechanism, On Error Resume Next. Create a variable to specify the remote computer name. This script uses almost the same code used in most scripts in this paper. Here, though, it assigns “client1” (the name of the remote computer) to strComputer instead of “.” (the WMI name for the local computer). WMI also accepts IP addresses as the identifier of the remote computer. To run this script, replace "client1" with the name or IP address of an accessible 3. 4. remote computer on which you have administrative privileges. Create a WshShell object and assign it to objShell. Run the Exec method of objShell, passing it parameters that call for sending two echo requests, with a wait of 1000 milliseconds (one second) for each response, to the target 5. computer. Assign the resulting object to objExec. Read the entire StdOut stream produced by the objExec object, convert it to lowercase to 6. avoid case confusion, and assign the stream to the variable strPingResults. Call the InStr function of VBScript, which searches the first parameter, the string of results from the Ping for any occurrences of the second parameter, the literal string "reply from." If the literal is found, then Ping succeeded, and the target computer responded. InStr returns the character position in the first string in which the second string is found; if it is not found, InStr returns 0. The If...Then statement interprets any number except zero as True for its condition, the script then executes the lines of code that follow before Else (8–15). Because the target computer has responded, the script can connect to WMI on the target and display its name. This is just a simple example: after the script connects to the target computer, it can perform any set of 7. WMI and ADSI tasks. If InStr does not find the string "reply from" and returns 0, then the remote computer has not responded to the Ping. In this case, the If...Then statement transfers script execution to the Else statement on line 16, and the script displays a message that the target did not respond to the ping. The script does not try to connect to WMI or perform the task on the remote computer because doing so would result in an error. Listing 15 Ping.vbs
  33. 33. 1 On Error Resume Next 2 3 strTarget = "192.168.0.1" 'IP address or hostname 4 Set objShell = CreateObject("WScript.Shell") 5 Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget) 6 strPingResults = LCase(objExec.StdOut.ReadAll) 7 If InStr(strPingResults, "reply from") Then 8 WScript.Echo strTarget & " responded to ping." 9 Set objWMIService = GetObject("winmgmts:" _ 10 11 & "{impersonationLevel=impersonate}!" & strTarget & "rootcimv2") Set colCompSystems = objWMIService.ExecQuery("SELECT * FROM " & _ 12 13 "Win32_ComputerSystem") For Each objCompSystem In colCompSystems 14 15 WScript.Echo "Host Name: " & LCase(objCompSystem.Name) Next 16 Else 17 WScript.Echo strTarget & " did not respond to ping." 18 End If When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>ping.vbs 192.168.0.1 responded to ping. Host Name: server1 Pinging Multiple Network Hosts by Running Ping.exe from a Script With a few more lines of code, a script can ping multiple computers one at a time before attempting to perform a task on each. The computer names are passed to the script in the form of an array, which is a simple way to accomplish this. However, the computer names can also be retrieved from a text file, spreadsheet, or database; or they can be enumerated from an Active Directory organizational unit (OU) by using only a little more code. Scripting Steps Listing 15 illustrates how to run Ping.exe with the WshShell Exec() method against multiple computers. 1. 2. Invoke On Error Resume Next, which is the error-handling mechanism for VBScript. Create an array with the VBScript Array function and add as elements the names or IP addresses of accessible computers on the network. The WMI service accepts both host names 3. and IP addresses in the object path on line 12. Assign the array to the variable arrTargets. Use a For Each loop to iterate through each element in the array. For each computer name,
  34. 34. perform the same steps performed on the remote computer in the previous example, Ping.vbs. Listing 15 Ping-multi.vbs 1 On Error Resume Next 2 3 arrTargets = Array("192.168.0.1", "192.168.0.11", "192.168.0.12", _ 4 "192.168.0.13") 5 6 For Each strTarget In arrTargets 7 Set objShell = CreateObject("WScript.Shell") 8 Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget) 9 strPingResults = LCase(objExec.StdOut.ReadAll) 10 If InStr(strPingResults, "reply from") Then 11 WScript.Echo VbCrLf & strTarget & " responded to ping." 12 Set objWMIService = GetObject("winmgmts:" _ 13 & "{impersonationLevel=impersonate}!" & strTarget & "rootcimv2") 14 Set colCompSystems = objWMIService.ExecQuery("SELECT * FROM " & _ 15 "Win32_ComputerSystem") 16 For Each objCompSystem In colCompSystems 17 WScript.Echo "Host Name: " & LCase(objCompSystem.Name) 18 19 Next Else 20 21 WScript.Echo VbCrLf & strTarget & " did not respond to ping." End If 22 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>ping-multi.vbs 192.168.0.1 responded to ping. Host Name: server1 192.168.0.11 responded to ping. Host Name: client1
  35. 35. 192.168.0.12 responded to ping. Host Name: client2 192.168.0.13 did not respond to ping. Pinging a Single Network Host by Using the Win32_PingStatus Class On Windows XP and Windows Server 2003, the new WMI class Win32_PingStatus can return more details of the ping operation than those provided by Ping.exe. However, you can only use this WMI class on a network that is running just these two operating systems. In such a situation, this script can serve as a template for testing a single remote computer for connectivity with a ping before attempting to connect to WMI and perform tasks on it. The StatusCode property of Win32_PingStatus returns the status codes shown in Table 6. Their data type is uint32 and they are read-only. To make this script more user-friendly, you can translate the status codes into the descriptive string that appears in Table 6. Table 6 Win32_Pingstatus Status Codes Value Description 0 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11032 11050 Success Buffer Too Small Destination Net Unreachable Destination Host Unreachable Destination Protocol Unreachable Destination Port Unreachable No Resources Bad Option Hardware Error Packet Too Big Request Timed Out Bad Request Bad Route TimeToLive Expired Transit TimeToLive Expired Reassembly Parameter Problem Source Quench Option Too Big Bad Destination Negotiating IPSEC General Failure Scripting Steps Listing 16 illustrates how to use the Win32_PingStatus class to test the connectivity of a remote computer and display information about the ping results that the properties of this class can return. 1. 2. 3. 4. Invoke the VBScript error-handling mechanism, On Error Resume Next. Create a variable to specify the name of the computer that runs the script. Create a variable to specify the name of the target computer to be pinged. Connect to the WMI service on the computer where you run the script. This example runs the script on the local computer (".") and targets the local loopback address ("127.0.0.1"), but you can run this script on a remote computer and ping another remote 5. computer. Call the ExecQuery method of the WMI service object, passing it a WQL query that requests all properties (*) from the instance of Win32_PingStatus where the address is that of the target computer. Assign the resulting collection of instances (in this example, just one instance results) to the variable colPings.
  36. 36. The Win32_PingStatus is unusual within WMI in that you do not call a method to perform actions with it. Rather, you simply query the class, filtering with WHERE for the instance where the value of Address, which is one of the key properties, is the name or IP address of the target computer. You can also filter for several other key properties to configure the ping. By 6. running such a query, the script initiates the ping operation. If no error occurs in querying the Win32_PingStatus class, iterate through the collection of 7. ping objects (there is only one by nature of the query). If no error occurs in iterating through the collection of ping objects, check the status code 8. returned by the ping object. If the status code is 0, which indicates that the target responded to the ping, display several of 9. the properties returned by the ping object. If an error occurs, either in querying the Win32_PingStatus class or in iterating through the collection of ping objects, clear the status code and display the status code description. Listing 16 Pingstatus.vbs
  37. 37. 1 On Error Resume Next 2 3 strComputer = "." 4 strTarget = " client1" 'IP address or hostname 5 Set objWMIService = GetObject("winmgmts:" _ 6 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 7 Set colPings = objWMIService.ExecQuery _ 8 ("Select * From Win32_PingStatus where Address = '" & strTarget & "'") 9 If Err = 0 Then 10 Err.Clear 11 For Each objPing in colPings 12 If Err = 0 Then 13 Err.Clear 14 If objPing.StatusCode = 0 Then 15 Wscript.Echo strTarget & " responded to ping." 16 Wscript.Echo "Responding Address: " & objPing.ProtocolAddress 17 Wscript.Echo "Responding Name: " & objPing.ProtocolAddressResolved 18 Wscript.Echo "Bytes Sent: " & objPing.BufferSize 19 Wscript.Echo "Time: " & objPing.ResponseTime & " ms" 20 Wscript.Echo "TTL: " & objPing.ResponseTimeToLive & " seconds" 21 Else 22 WScript.Echo strTarget & " did not respond to ping." 23 WScript.Echo "Status Code: " & objPing.StatusCode 24 End If 25 Else 26 Err.Clear 27 WScript.Echo "Unable to call Win32_PingStatus on " & strComputer & "." 28 29 End If Next 30 Else 31 Err.Clear
  38. 38. When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: Automating TCP/IP Networking on Clients Part 4: Scripting IP Address Allocation on Clients Published: July 12, 2004 At the heart of TCP/IP networking is the allocation of IP addresses. If your network uses Dynamic Host Configuration Protocol (DHCP), you are already using a form of automation to manage this critical function. In the early days of TCP/IP networking, administrators assigned IP addresses manually. As networks grew and became more complex, this became impractical. Early efforts to automate this function, such as Reverse Address Resolution Protocol (RARP) and Bootstrap Protocol (BOOTP), still required considerable manual configuration. DHCP was developed to replace them and extend their functionality into a client/server protocol capable of managing an IP address pool and related client configuration parameters with much less administrative intervention. Today, on most networks of any size, DHCP is the default way to automate the management of IP address configuration. Even when your network uses DHCP, though, you may still need to use static IP addresses in certain cases, such as exclusions. In addition, some smaller or older networks may use only static IP addresses. DHCP servers and clients also interact with other TCP/IP components in significant ways. For example, when using DNS dynamic update, DHCP clients and servers update DNS servers with changes in IP addresses to ensure that name resolution remains accurate as IP address leases are released and renewed. Here, as with most TCP/IP settings, you can manually make changes on a local computer by using the Windows interface. For example, as Figure 9 illustrates, you can configure DHCP settings on the IP Settings tab of the Advanced TCP/IP Settings dialog box.
  39. 39. into a long string and display the string with WScript.Echo. Listing 19 Dhcpsettings.vbs
  40. 40. 1 On Error Resume Next 2 3 strComputer = "." 4 5 Set objWMIService = GetObject("winmgmts:" _ 6 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 7 Set colNicConfigs = objWMIService.ExecQuery _ 8 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 9 10 For Each objNicConfig In colNicConfigs 11 strDNSHostName = objNicConfig.DNSHostName 12 strIndex = objNicConfig.Index 13 strDescription = objNicConfig.Description 14 blnDHCPEnabled = objNicConfig.DHCPEnabled 15 If blnDHCPEnabled Then 16 strDHCPServer = objNicConfig.DHCPServer 17 dtmRawLeaseObtainedDate = objNicConfig.DHCPLeaseObtained 18 strDHCPLeaseObtained = WMIDateToString(dtmRawLeaseObtainedDate) 19 dtmRawLeaseExpiresDate = objNicConfig.DHCPLeaseExpires 20 strDHCPLeaseExpires = WMIDateToString(dtmRawLeaseExpiresDate) 21 End If 22 strDHCPSettings = strDHCPSettings & VbCrLf & VbCrLf & _ 23 " 24 " " & strDescription & VbCrLf & VbCrLf & _ 25 " DHCP Enabled: 26 27 Network Adapter " & strIndex & VbCrLf & _ " & blnDHCPEnabled If blnDHCPEnabled Then strDHCPSettings = strDHCPSettings & VbCrLf & _ 28 " DHCP Server: " & strDHCPServer & VbCrLf & _ 29 " DHCP Lease Obtained: " & strDHCPLeaseObtained & VbCrLf & _ 30 " DHCP Lease Expires: 31 End If " & strDHCPLeaseExpires
  41. 41. When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>dhcpsettings.vbs DHCP Settings Host Name: client1 Network Adapter 1 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack et Scheduler Miniport DHCP Enabled: DHCP Server: True 192.168.0.1 DHCP Lease Obtained: 5/13/2004 6:34:24 PM DHCP Lease Expires: 5/23/2004 9:34:24 PM Enabling DHCP on a Client Automating the configuration of DHCP on clients may be worthwhile when a remote client or group of remote clients must be converted from using a static IP address to obtaining the IP address automatically. Depending on how the DHCP and DNS servers are configured, enabling DHCP may also enable the client to obtain the DNS server and default gateway addresses from the DHCP server. The following script shows how to use EnableDHCP, which is a method of Win32_NetworkAdapterConfiguration that enables DHCP for service on the network adapter of a client. The method takes no parameters. For a client with more than one network adapter, such as a dual-homed computer, you can adapt the script to enable only a certain adapter. Scripting Steps Caution This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it. Listing 20 enables DHCP on each network adapter configuration on a computer. 1. Use a GetObject call to connect to the WMI namespace rootcimv2 on the specified 2. computer, and set the impersonation level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.” This returns a collection consisting of all the network adapter configurations on the 3. 4. 5. 6. computer for which IP is enabled. Perform the following tasks for each network adapter configuration in the collection. Display the index number and description of the network adapter. Check whether DHCP is already enabled. If DHCP is not enabled, call the EnableDHCP method of 7. Win32_NetworkAdapterConfiguration. If the EnableDHCP method returns: • • A value of 0, display a message indicating success. Any value other than 0, display a message indicating failure.
  42. 42. 8. If DHCP is already enabled, display a message to that effect with the IP address of the DHCP server. Listing 20 Dhcp-enable.vbs 1 On Error Resume Next 2 3 strComputer = "." 4 Set objWMIService = GetObject("winmgmts:" _ 5 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 6 Set colNicConfigs = objWMIService.ExecQuery _ 7 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 8 9 For Each objNicConfig In colNicConfigs 10 WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & _ 11 VbCrLf & " 12 " & objNicConfig.Description & VbCrLf If Not objNicConfig.DHCPEnabled Then 13 WScript.Echo " 14 Enabling DHCP ..." intReturn = objNicConfig.EnableDHCP 15 If intReturn = 0 Then 16 strSuccess = " DHCP enabled." 17 Else 18 strSuccess = " Unable to enable DHCP." 19 End If 20 WScript.Echo VbCrLf & strSuccess 21 22 Else 23 WScript.Echo " 24 " DHCP already enabled" & VbCrLf & _ DHCP Server: " & objNicConfig.DHCPServer 25 End If 26 Next When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:
  43. 43. C:scriptsnetcli>dhcp-enable.vbs Network Adapter 1 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack et Scheduler Miniport Enabling DHCP ... DHCP enabled. Managing DHCP Leases DHCP usually allocates IP addresses only for specified time periods. This temporary address allocation is called a lease. Administrators of a DHCP server can configure the default term of a lease, contingent on factors like how often you add or remove network clients, or the number of addresses and clients on a subnet. DHCP clients and servers are designed to automatically renegotiate leases before they expire. You can also release or renew leases manually or programmatically. For example, the command-line tool Ipconfig.exe provides parameters for that purpose. Win32_NetworkAdapterConfiguration provides four per-adapter methods that enable you to manage DHCP leases on its instances: ReleaseDHCPLease, ReleaseDHCPLeaseAll, RenewDHCPLease and RenewDHCPLeaseAll. You can also release or renew all leases simply by iterating through the collection of network adapter configurations and using ReleaseDHCPLease or RenewDHCPLease on each. Releasing DHCP Leases Releasing a DHCP lease for a network adapter disconnects that adapter from the network and releases the IP address for assignment to other hosts. The ipconfig.exe /release command performs this task on all network adapters or on a specified adapter. One situation in which you might want to release a DHCP lease on a client is when reserving a scope (a range of IP addresses) on a DHCP server for permanent lease assignment. Some of the addresses being reserved in the scope may already be in use by existing clients that will not be included in the scope. Yet adding an IP address to a scope on the DHCP server does not automatically release the address on the client that currently holds it. The script below illustrates one way to handle this problem. It iterates through the collection of network adapter configurations and uses the ReleaseDHCPLease method to release the lease of each. You can easily adapt this script to release the lease on a remote client by changing the following line: strComputer = "." In place of the local computer ("."), substitute the IP address that needs to be freed for the reservation; for example: strComputer = "192.168.0.135" As with all remote WMI operations, the user must have appropriate administrative privileges on the remote computer. Scripting Steps Caution This script may make changes in your computer configuration. Run it only on a test computer and
  44. 44. note the settings involved before running it. Listing 21 first displays DHCP settings for each network adapter. It then checks each network adapter to see whether DHCP is enabled and if it is, releases the DHCP lease. 1. Use a GetObject call to connect to the WMI namespace rootcimv2 on the specified 2. computer, and set the impersonation level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.” This returns a collection that consists of all the network adapter configurations for the 3. 4. 5. 6. computer on which IP is enabled. Display the label "Settings before releasing lease." Perform the following steps for each network adapter configuration in the collection. Display the index number, description, and whether DHCP is enabled for each adapter. If DHCP is enabled, retrieve the dates the DHCP lease was obtained and will expire and convert them to a readable format by calling the WMIDateToString function. 7. Display the IP address of the DHCP server and the lease dates. Call the ReleaseDHCPLease method of Win32_NetworkAdapterConfiguration, then wait 5 seconds for the release process to finish. Important If a client is using DHCP to obtain an IP address, releasing the lease may disconnect the 8. client from the network. If the ReleaseDHCPLease method returns: • • • 9. A value of 0, display a message that the lease has been released. A value greater than 1, display a message that the lease cannot be released. A value of 1, display a message that the lease has been released and that the computer must be rebooted. Requery the Win32_NetworkAdapterConfiguration class, filtering again for only IP-enabled adapters. This requery is necessary because each query returns a snapshot of the settings that it found at the moment the query ran and does not automatically update the query if 10. 11. settings subsequently change. Redisplay the same DHCP-related settings as were previously displayed. The WMIDateToString function takes a value in WMI DATETIME format and converts it into a string expressing the date and time in a more readable format. Listing 21 Dhcp-releaselease.vbs
  45. 45. 1 On Error Resume Next 2 3 strComputer = "." 4 Set objWMIService = GetObject("winmgmts:" _ 5 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 6 Set colNicConfigs = objWMIService.ExecQuery _ 7 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 8 9 WScript.Echo VbCrLf & "Settings before releasing lease" 10 11 For Each objNicConfig In colNicConfigs 12 13 blnDHCPEnabled = objNicConfig.DHCPEnabled 14 15 WScript.Echo VbCrLf & _ 16 " Network Adapter " & objNicConfig.Index & VbCrLf & _ 17 " " & objNicConfig.Description & VbCrLf & VbCrLf & _ 18 " DHCP Enabled: " & blnDHCPEnabled 19 20 If blnDHCPEnabled Then 21 22 dtmLeaseObtainedDate = objNicConfig.DHCPLeaseObtained 23 strDHCPLeaseObtained = WMIDateToString(dtmLeaseObtainedDate) 24 dtmLeaseExpiresDate = objNicConfig.DHCPLeaseExpires 25 strDHCPLeaseExpires = WMIDateToString(dtmLeaseExpiresDate) 26 27 WScript.Echo " DHCP Server: " & objNicConfig.DHCPServer & _ 28 VbCrLf & " DHCP Lease Obtained: " & strDHCPLeaseObtained & _ 29 VbCrLf & " DHCP Lease Expires: " & strDHCPLeaseExpires 30 31 intReleaseReturn = objNicConfig.ReleaseDHCPLease
  46. 46. When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>dhcp-releaselease.vbs Settings before releasing lease Network Adapter 1 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack et Scheduler Miniport DHCP Enabled: DHCP Server: True 192.168.0.1 DHCP Lease Obtained: 5/30/2004 8:41:23 PM DHCP Lease Expires: 6/9/2004 11:41:23 PM DHCP lease released. Settings after releasing lease Network Adapter 1 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack et Scheduler Miniport DHCP Enabled: DHCP Server: True 255.255.255.255 DHCP Lease Obtained: 6/1/2004 2:15:08 PM DHCP Lease Expires: 6/1/2004 3:15:08 PM Renewing DHCP Leases DHCP also allows leases to be manually or programmatically renewed on the client, bypassing the normal renegotiation process between client and server. The ipconfig.exe /renew command performs this task for all network adapters or a specified adapter. The following script iterates through the collection of network adapter configurations and uses the RenewDHCPLease method to renew the lease of each. Scripting Steps Caution This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it. Listing 22 first displays DHCP settings for each network adapter; it then checks each network adapter to see if DHCP is enabled. If it is, it renews the DHCP lease. To carry out this task, the script must: 1. Use a GetObject call to connect to the WMI namespace rootcimv2 on the specified 2. computer, and set the impersonation level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”
  47. 47. This returns a collection consisting of all the network adapter configurations on the 3. 4. 5. 6. computer for which IP is enabled. Display the label "Settings before renewing lease." Perform the following steps for each network adapter configuration in the collection. Display the index number, description, and whether DHCP is enabled for each adapter. If DHCP is enabled, retrieve the dates the DHCP lease was obtained and will expire and convert them to a readable format by calling the WMIDateToString function. 7. Display the IP address of the DHCP server and the lease obtention and expiration dates. Call the RenewDHCPLease method of Win32_NetworkAdapterConfiguration, then wait 5 8. seconds for the renewal process to finish. If the RenewDHCPLease method returns: • • • 9. A value of 0, display a message that the lease has been renewed. A value greater than 1, display a message that the lease cannot be renewed. A value of 1, display a message that the lease has been renewed and that the computer must be rebooted. Requery the Win32_NetworkAdapterConfiguration class, filtering again for only IP-enabled adapters. This requery is necessary because each query returns a snapshot of the settings it found at the moment the query ran and does not automatically update itself if settings 10. 11. subsequently change. Redisplay the same DHCP-related settings as were previously displayed. The WMIDateToString function takes a value in WMI DATETIME format and converts it into a string expressing the date and time in a more readable format. Listing 22 Dhcp-renewlease.vbs
  48. 48. 1 On Error Resume Next 2 3 strComputer = "." 4 Set objWMIService = GetObject("winmgmts:" _ 5 & "{impersonationLevel=impersonate}!" & strComputer & "rootcimv2") 6 Set colNicConfigs = objWMIService.ExecQuery _ 7 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") 8 9 WScript.Echo VbCrLf & "Settings before renewing lease" 10 11 For Each objNicConfig In colNicConfigs 12 13 blnDHCPEnabled = objNicConfig.DHCPEnabled 14 15 WScript.Echo VbCrLf & _ 16 " Network Adapter " & objNicConfig.Index & VbCrLf & _ 17 " " & objNicConfig.Description & VbCrLf & VbCrLf & _ 18 " DHCP Enabled: " & blnDHCPEnabled 19 20 If blnDHCPEnabled Then 21 22 dtmLeaseObtainedDate = objNicConfig.DHCPLeaseObtained 23 strDHCPLeaseObtained = WMIDateToString(dtmLeaseObtainedDate) 24 dtmLeaseExpiresDate = objNicConfig.DHCPLeaseExpires 25 strDHCPLeaseExpires = WMIDateToString(dtmLeaseExpiresDate) 26 27 WScript.Echo " DHCP Server: " & objNicConfig.DHCPServer & _ 28 VbCrLf & " DHCP Lease Obtained: " & strDHCPLeaseObtained & _ 29 VbCrLf & " DHCP Lease Expires: " & strDHCPLeaseExpires 30 31 intRenewReturn = objNicConfig.RenewDHCPLease
  49. 49. When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: C:scripts>dhcp-renewlease.vbs Settings before renewing lease Network Adapter 1 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack et Scheduler Miniport DHCP Enabled: DHCP Server: True 255.255.255.255 DHCP Lease Obtained: 6/1/2004 2:15:08 PM DHCP Lease Expires: 6/1/2004 3:15:08 PM DHCP lease renewed. Settings after renewing lease Network Adapter 1 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack et Scheduler Miniport DHCP Enabled: DHCP Server: True 192.168.0.1 DHCP Lease Obtained: 6/1/2004 2:15:56 PM DHCP Lease Expires: 6/11/2004 5:15:56 PM Top of page Managing Static IP Addresses On very small networks, DHCP may be overkill and you may be able to manage IP address allocation by assigning static IP addresses to all your clients. Even on larger and more complex networks, some hosts — such as network servers and domain controllers — cannot use DHCP and must be assigned static IP addresses. These static IP addresses must also be added to the list of exclusions from the scope on the DHCP server. As with most other areas of network client configuration, the Win32_NetworkAdapterConfiguration WMI class provides methods that can programmatically read and write these settings. Configuring a Static IP Address The script in this section, Staticip-enable.vbs, uses the EnableStatic() method of Win32_NetworkAdapterConfiguration to set the network adapter’s IP addresses and subnet masks, which are exposed in the form of the properties IPAddress and IPSubnet. Because these settings can have more than one value, the data types of these two properties are a string array. The EnableStatic() method also effectively disables DHCP. This script shows the basic code involved in accomplishing this task; however, a client that is assigned a static IP address must also be
  50. 50. assigned a default gateway and DNS server before it can reestablish network connectivity. The script in the next section, Staticip-enableex.vbs, shows how to script this sequence of tasks. Both of these scripts do not assign a new static IP address if a static address is already enabled. However, if you need to assign a new static IP address when another static address is already configured, you can easily adapt the script by removing the following lines: If objNicConfig.DHCPEnabled Then ... Else WScript.Echo " Static IP address already enabled." End If Scripting Steps Caution This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it. Listing 23 checks each network adapter to see if DHCP is enabled. If it is, the script enables static IP addressing, assigning an IP address and subnet mask, and effectively disabling DHCP on the client. The configuration changes may need to be propagated to the DHCP server as well, so that the old IP address leased from DHCP is released and the new static IP address is registered. The technique illustrated in this script is not sufficient in itself to reestablish network connectivity with a static IP address. Default gateway and DNS servers must also be set, as the next script does. With this script, you would have to set them manually. To disable DHCP and assign a static IP address and subnet mask to a client, the script must: 1. Create two one-element arrays: the first contains the static IP address to be assigned; the 2. second contains the subnet mask. Use a GetObject call to connect to the WMI namespace rootcimv2 on the specified 3. computer, and set the impersonation level to “impersonate.” Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.” This returns a collection consisting of all the network adapter configurations on the 4. computer for which IP is enabled. Loop through each network adapter configuration in the collection, performing the following 5. 6. steps on each. Display the index number and description of the network adapter. If DHCP is enabled on the adapter, call the EnableStatic method of Win32_NetworkAdapterConfiguration, passing it the two array variables already initialized 7. with the IP addresses and subnet masks that you need. If EnableStatic returns: • • • 8. 9. A value of 0, indicating success, display the new IP addresses and subnet masks. A value other than 0 or 1, indicating failure, display a message to that effect. A value of 1, display a success message indicating that the machine must be rebooted, and increment the reboot counter. If DHCP is not enabled, display a message that static IP addressing is already enabled. If the reboot counter is greater than 0, then for at least one network adapter the return value of EnableStatic was 1. Display a message that the computer must be rebooted before
  51. 51. changes will take effect. Listing 23 Staticip-enable.vbs

×