Part 4: Scripting IP Address Allocation on Clients
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.
Figure 9 Configuring DHCP Setting by Using the Windows Interface
As previously mentioned, you can also use the command-line tool Ipconfig.exe to retrieve DHCP client settings, release and renew leases, and perform other DHCP client tasks. For remote and multiple clients, though, as well as for complex local tasks that risk manual errors, scripting may be a more efficient alternative.
This section discusses how to script the management of IP address allocation by using both DHCP and static addressing. This paper covers only how to configure clients, although in some cases, the changes on clients also require changes on the DHCP servers. Management of DHCP servers is not covered in this paper.
On This Page
Managing DHCP on Clients
Managing Static IP Addresses
Scenario: Allocating IP Addresses on a Subnet
Scenario: Switching Between a Static IP Address and DHCP
Tools for IP Address Allocation on Clients
Managing DHCP on Clients
Although DHCP is already a form of automation, scripting can help you automate the configuration of groups of clients to take advantage of DHCP. Through the properties and methods provided by the WMI class Win32_NetworkAdapterConfiguration, you can enumerate DHCP settings, enable or disable DHCP, and renew or release releases.
Table 9 describes the Win32_NetworkAdapterConfiguration properties that you can use for IP address allocation.
Table 9 Win32_NetworkAdapterConfiguration IP Address Allocation Properties
Property |
Type |
Description |
---|---|---|
DefaultIPGateway |
String array |
Array of IP addresses of default gateways that the computer system uses. |
DHCPEnabled |
Boolean |
If TRUE, the DHCP server automatically assigns an IP address to the computer system when establishing a network connection. |
DHCPLeaseExpires |
Datetime |
Expiration date and time for a leased IP address that was assigned to the computer by the DHCP server. |
DHCPLeaseObtained |
Datetime |
The date and time that the lease was obtained for the IP address assigned to the computer by the DHCP server. |
DHCPServer |
String |
IP address of the DHCP server. |
GatewayCostMetric |
Uint16 |
Array of integer cost metric values (ranging from 1 to 9999) to be used in calculating the fastest, most reliable, or least expensive routes. This argument has a one-to-one correspondence with the DefaultIPGateway property. |
IPConnectionMetric (New in Windows XP) |
Uint32 |
Cost of using the configured routes for the IP bound adapter and is the weighted value for those routes in the IP routing table. If there are multiple routes to a destination in the IP routing table, the route with the lowest metric is used. The default value is 1. |
IPAddress |
String |
Array of all of the IP addresses associated with the current network adapter. |
IPSubnet |
String |
Array of all the subnet masks associated with the current network adapter. |
All the properties in the previous table are read-only. The types uint16 and uint32 are unsigned integer types that are used by strongly-typed programming languages; VBScript effectively treats them as integers.
Table 10 describes the Win32_NetworkAdapterConfiguration methods that you can use for IP address allocation.
Table 10 Win32_NetworkAdapterConfiguration IP Address Allocation Methods
Method |
Parameters |
Description |
---|---|---|
EnableDHCP |
None |
Enables DHCP for service with this network adapter. DHCP allows IP addresses to be dynamically allocated. |
EnableStatic |
IPAddress – array of strings SubnetMask – array of strings |
Enables static TCP/IP addressing for the target network adapter. As a result, DHCP for this network adapter is disabled. |
ReleaseDHCPLease |
None |
Releases the IP address bound to a specific DHCP-enabled network adapter. Caution If DHCP is enabled on the local computer, this option disables TCP/IP on the specific network adapter. Unless you have an alternate path to the target system, that is, another TCP/IP bound network adapter, all TCP/IP communications will be lost. |
ReleaseDHCPLeaseAll |
None |
Static method. Releases the IP addresses bound to all DHCP-enabled network adapters. Caution If DHCP is enabled on the local computer, this option terminates all DHCP TCP/IP connections. |
RenewDHCPLease |
None |
Renews the IP address on specific DHCP-enabled network adapters. The lease for the IP address assigned by a DHCP server has an expiration date that the client must renew if it intends to continue use of the assigned IP address. |
RenewDHCPLeaseAll |
None |
Static method. Renews the IP addresses on all DHCP-enabled network adapters. The lease for the IP address assigned by a DHCP server has an expiration date that the client must renew if it intends to continue use of the assigned IP address. |
SetGateways |
DefaultIPGateway – array of strings GatewayCostMetric – unit16 |
Specifies a list of gateways for routing packets to a subnet that is different from the subnet that the network adapter is connected to. This method only works when the network adapter is in static IP mode. |
All the methods in the previous table return a positive integer:
0 indicates successful completion.
1 indicates successful completion with reboot required.
Numbers greater than 1 indicate that some problem was encountered and the method could not complete. The WMI SDK lists the meanings of return values for these methods.
Displaying DHCP Client Information
When you are working with a technology like DHCP, the first step in scripting is usually to determine the current configuration of settings relevant to it. This is the approach that is taken in this section and in those that follow.
Win32_NetworkAdapterConfiguration provides per-adapter properties that show whether DHCP is enabled; the IP address of the DHCP server; the date and time when the lease was obtained and when it will expire; and the client IP addresses and subnet masks (network adapters can have more than one of each).
Because WMI returns dates and times in a format that is not designed for easy reading, displaying lease dates and times requires converting the WMI date and time format to a more user-friendly one.
The following script displays IP address allocation settings for a network client by using the following properties of Win32_NetworkAdapterConfiguration: DHCPEnabled, DHCPServer, DHCPLeaseObtained, DHCPLeaseExpires, IPAddress, and IPSubnet. The script displays settings for DHCPServer, DHCPLeaseObtained, and DHCPLeaseExpires only if DHCP is enabled.
Rather than directly displaying the settings with the WSH WScript.Echo method, the script assigns them to a string and displays them after they have been collected. Then, after verifying with an If ... Then clause that DHCPEnabled is True, the script displays the subordinate settings.
Two of the settings displayed by Dhcpsettings.vbs, DHCPLeaseObtained and DHCPLeaseExpires, are returned as a DATETIME value. If you display the raw value, it look likes this:
20021201000230.000000+000
The first four digits represent the year, the next two the month, the next two the day, then hours, minutes, seconds, and so on. You can figure out what it means — although it is not quick and easy to read.
Windows XP and Windows Server 2003 have added a new SWbemDateTime object to the WMI Scripting API. This object makes it easier to parse and convert datetime values if all your clients are running Windows XP and Windows Server 2003.
However, if not all your network hosts are running Windows XP or Windows Server 2003, a more convenient and less complicated solution is to parse datetime values into a readable format by using the string manipulation capabilities of VBScript.
In this script, to convert the datetime value into something more readable, Dhcpsettings calls a function, WMIDateToString(), and passes it the datetime value as a parameter. The function transforms the value with the VBScript built-in Mid() and Left() string functions. It then calls the VBScript CDate() function to cast the variant value (the type of all VBScript variables) as a sub-type Date, and returns the formatted date to the main body of the script.
For more information about the WMI DATETIME format, see "Setting the Time on One Computer by Using WMI" later in this document.
Scripting Steps
Listing 19 displays the DHCP settings for each network adapter configuration on a computer.
Create a variable and assign the name of a computer to it. For the local computer, simply specify "." as the computer name. To run this script remotely, specify the name of an accessible remote computer on your network on which you have administrative privileges. The name can be in the form of either a host name or an IP address.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified 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 computer for which IP is enabled.
For each network adapter configuration in the collection, perform the following tasks.
Call the Get method on objWMIService to obtain an object reference to the instance of Win32_NetworkAdapter whose DeviceID property is equal to the Index property of the current instance of Win32_NetworkAdapterConfiguration.
Get the value of the DNSHostName property of Win32_NetworkAdapterConfiguration and assign it to a variable.
Get the value of the NetConnectionID property of Win32_NetworkAdapter and assign it to a variable. If this raises an error, use the Index property of Win32_NetworkAdapterConfiguration instead.
Get the DHCPEnabled property of Win32_NetworkAdapterConfiguration and assign it to a variable.
If the DHCPEnabled property is True, meaning that DHCP is enabled on the current network adapter, get the other properties related to IP address allocation and assign them to variables.
For the DHCPLeaseObtained and DHCPLeaseExpires properties of Win32_NetworkAdapterConfiguration, pass their values as a parameter to the WMIDateToString function. This function converts the DATETIME format returned by these two properties into more readable strings.
Concatenate the variables containing the values of the properties with explanatory labels into a long string and display the string with WScript.Echo.
Listing 19 Dhcpsettings.vbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
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: True
DHCP Server: 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.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified 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 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 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.
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
On Error Resume Next strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\" & strComputer & "\root\cimv2") Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & _ VbCrLf & " " & objNicConfig.Description & VbCrLf If Not objNicConfig.DHCPEnabled Then WScript.Echo " Enabling DHCP ..." intReturn = objNicConfig.EnableDHCP If intReturn = 0 Then strSuccess = " DHCP enabled." Else strSuccess = " Unable to enable DHCP." End If WScript.Echo VbCrLf & strSuccess Else WScript.Echo " DHCP already enabled" & VbCrLf & _ " DHCP Server: " & objNicConfig.DHCPServer End If Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:
C:\scripts\netcli>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 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.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified 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 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.
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 client from the network.If the ReleaseDHCPLease method returns:
A value of 0, display a message that the lease has been released.
A value of 1, display a message that the lease has been released and that the computer must be rebooted.
A value greater than 1, display a message that the lease cannot be released.
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 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
On Error Resume Next strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") WScript.Echo VbCrLf & "Settings before releasing lease" For Each objNicConfig In colNicConfigs blnDHCPEnabled = objNicConfig.DHCPEnabled WScript.Echo VbCrLf & _ " Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf & VbCrLf & _ " DHCP Enabled: " & blnDHCPEnabled If blnDHCPEnabled Then dtmLeaseObtainedDate = objNicConfig.DHCPLeaseObtained strDHCPLeaseObtained = WMIDateToString(dtmLeaseObtainedDate) dtmLeaseExpiresDate = objNicConfig.DHCPLeaseExpires strDHCPLeaseExpires = WMIDateToString(dtmLeaseExpiresDate) WScript.Echo " DHCP Server: " & objNicConfig.DHCPServer & _ VbCrLf & " DHCP Lease Obtained: " & strDHCPLeaseObtained & _ VbCrLf & " DHCP Lease Expires: " & strDHCPLeaseExpires intReleaseReturn = objNicConfig.ReleaseDHCPLease WScript.Sleep 5000 If (intReleaseReturn = 0 Or intReleaseReturn = 1) Then strSuccess = " DHCP lease released." If intReleaseReturn = 1 Then strSuccess = strSuccess & " Must reboot machine." End If Else strSuccess = " Unable to release DHCP lease." End If WScript.Echo VbCrLf & strSuccess End If Next Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") WScript.Echo VbCrLf & "Settings after releasing lease" For Each objNicConfig In colNicConfigs blnDHCPEnabled = objNicConfig.DHCPEnabled WScript.Echo VbCrLf & _ " Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf & VbCrLf & _ " DHCP Enabled: " & blnDHCPEnabled If blnDHCPEnabled Then dtmLeaseObtainedDate = objNicConfig.DHCPLeaseObtained strDHCPLeaseObtained = WMIDateToString(dtmLeaseObtainedDate) dtmLeaseExpiresDate = objNicConfig.DHCPLeaseExpires strDHCPLeaseExpires = WMIDateToString(dtmLeaseExpiresDate) WScript.Echo " DHCP Server: " & objNicConfig.DHCPServer & _ VbCrLf & " DHCP Lease Obtained: " & strDHCPLeaseObtained & _ VbCrLf & " DHCP Lease Expires: " & strDHCPLeaseExpires End If Next '****************************************************************************** ' Function: WMIDateToString(dtmDate) ' Converts WMI date to string. '****************************************************************************** Function WMIDateToString(dtmDate) WMIDateToString = CDate(Mid(dtmDate, 5, 2) & "/" & _ Mid(dtmDate, 7, 2) & "/" & _ Left(dtmDate, 4) & " " & _ Mid(dtmDate, 9, 2) & ":" & _ Mid(dtmDate, 11, 2) & ":" & _ Mid(dtmDate, 13, 2)) End Function
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: True
DHCP Server: 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: True
DHCP Server: 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:
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified 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 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.
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 seconds for the renewal process to finish.
If the RenewDHCPLease method returns:
A value of 0, display a message that the lease has been renewed.
A value of 1, display a message that the lease has been renewed and that the computer must be rebooted.
A value greater than 1, display a message that the lease cannot be renewed.
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 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
On Error Resume Next strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") WScript.Echo VbCrLf & "Settings before renewing lease" For Each objNicConfig In colNicConfigs blnDHCPEnabled = objNicConfig.DHCPEnabled WScript.Echo VbCrLf & _ " Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf & VbCrLf & _ " DHCP Enabled: " & blnDHCPEnabled If blnDHCPEnabled Then dtmLeaseObtainedDate = objNicConfig.DHCPLeaseObtained strDHCPLeaseObtained = WMIDateToString(dtmLeaseObtainedDate) dtmLeaseExpiresDate = objNicConfig.DHCPLeaseExpires strDHCPLeaseExpires = WMIDateToString(dtmLeaseExpiresDate) WScript.Echo " DHCP Server: " & objNicConfig.DHCPServer & _ VbCrLf & " DHCP Lease Obtained: " & strDHCPLeaseObtained & _ VbCrLf & " DHCP Lease Expires: " & strDHCPLeaseExpires intRenewReturn = objNicConfig.RenewDHCPLease WScript.Sleep 5000 If (intRenewReturn = 0 Or intRenewReturn = 1) Then strSuccess = " DHCP lease renewed." If intRenewReturn = 1 Then strSuccess = strSuccess & " Must reboot machine." End If Else strSuccess = " Unable to renew DHCP lease." End If WScript.Echo VbCrLf & strSuccess End If Next Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") WScript.Echo VbCrLf & "Settings after renewing lease" For Each objNicConfig In colNicConfigs blnDHCPEnabled = objNicConfig.DHCPEnabled WScript.Echo VbCrLf & _ " Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf & VbCrLf & _ " DHCP Enabled: " & blnDHCPEnabled If blnDHCPEnabled Then dtmLeaseObtainedDate = objNicConfig.DHCPLeaseObtained strDHCPLeaseObtained = WMIDateToString(dtmLeaseObtainedDate) dtmLeaseExpiresDate = objNicConfig.DHCPLeaseExpires strDHCPLeaseExpires = WMIDateToString(dtmLeaseExpiresDate) WScript.Echo " DHCP Server: " & objNicConfig.DHCPServer & _ VbCrLf & " DHCP Lease Obtained: " & strDHCPLeaseObtained & _ VbCrLf & " DHCP Lease Expires: " & strDHCPLeaseExpires End If Next '****************************************************************************** ' Function: WMIDateToString(dtmDate) ' Converts WMI date to string. '****************************************************************************** Function WMIDateToString(dtmDate) WMIDateToString = CDate(Mid(dtmDate, 5, 2) & "/" & _ Mid(dtmDate, 7, 2) & "/" & _ Left(dtmDate, 4) & " " & _ Mid(dtmDate, 9, 2) & ":" & _ Mid(dtmDate, 11, 2) & ":" & _ Mid(dtmDate, 13, 2)) End Function
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: True
DHCP Server: 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: True
DHCP Server: 192.168.0.1
DHCP Lease Obtained: 6/1/2004 2:15:56 PM
DHCP Lease Expires: 6/11/2004 5:15:56 PM
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 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:
Create two one-element arrays: the first contains the static IP address to be assigned; the second contains the subnet mask.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified 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 computer for which IP is enabled.
Loop through each network adapter configuration in the collection, performing the following 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 with the IP addresses and subnet masks that you need.
If EnableStatic returns:
A value of 0, indicating success, display the new IP addresses and subnet masks.
A value of 1, display a success message indicating that the machine must be rebooted, and increment the reboot counter.
A value other than 0 or 1, indicating failure, display a message to that effect.
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 changes will take effect.
Listing 23 Staticip-enable.vbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
On Error Resume Next strComputer = "." arrIPAddresses = Array("192.168.0.12") arrSubnetMasks = Array("255.255.255.0") intReboot = 0 Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & _ VbCrLf & " " & objNicConfig.Description & VbCrLf If objNicConfig.DHCPEnabled Then WScript.Echo " Disabling DHCP, enabling static IP address..." intReturn = objNicConfig.EnableStatic(arrIPAddresses, arrSubnetMasks) If intReturn = 0 Then strIPAddresses = Join(arrIPAddresses, ",") strSubnetMasks = Join(arrSubnetMasks, ",") WScript.Echo " DHCP disabled, static IP address enabled." & _ VbCrLf & " IP Addresses: " & strIPAddresses & VbCrLf & _ " Subnet Masks: " & strSubnetMasks ElseIf intReturn = 1 Then intReboot = intReboot + 1 WScript.Echo " DHCP disabled, static IP address enabled. " & _ VbCrLf & " Reboot required." Else WScript.Echo " Unable to enable static IP address." End If Else WScript.Echo " Static IP address already enabled." End If Next If (intReboot > 0) Then WScript.Echo VbCrLf & "You must reboot this machine before changes " & _ "will take effect." End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:
C:\scripts>staticip-enable.vbs
Network Adapter 1
3Com 3C918 Integrated Fast Ethernet Controller (3C905B-TX Compatible)
Disabling DHCP, enabling static IP ...
DHCP disabled, static IP address enabled.
Reboot required.
You must reboot this machine before changes will take effect.
Configuring Gateways, DNS, and WINS for Static IP Addresses
To reestablish network connectivity for a client after enabling static IP addressing and assigning an IP address and subnet mask, you must also set new default gateways, DNS server search order, and WINS servers (if WINS is used on the network). However, the script should perform the second set of tasks only if a static IP address and subnet have been successfully assigned. Therefore, scripting this task requires two layers of conditionality.
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 24 checks each network adapter to see if DHCP is enabled. If it is, the script enables a static IP address, assigning the IP address and subnet mask and disabling DHCP. If the script succeeds with these tasks, it then assigns a default gateway, and DNS and WINS servers.
Create variables to specify all necessary parameters.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified 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 computer for which IP is enabled.
Loop through each network adapter configuration in the collection, performing the following 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 with the desired IP addresses and subnet masks.
If the return value of EnableStatic is 0, indicating success, call the Get method on Win32_NetworkAdapterConfiguration to return just the current instance, filtering with the Index property, which is the key property that WMI uses to uniquely identify the instance.
For the current instance of the network adapter, call the SetGateways, SetDNSServerSearchOrder, and SetWINSServer methods, passing them the appropriate variables as parameters.
Check the return values for each of these methods, and display a message indicating success or failure for each.
If EnableStatic returns:
A value of 1, display a success message indicating that the machine must be rebooted, and increment the reboot counter.
A value other than 0 or 1, indicating failure, display a message to that effect.
If DHCP is not enabled, display a message that static IP addressing is already enabled.
If the reboot counter returns:
A value 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 the changes can take effect and quit the script.
A value of 0, requery Win32_NetworkAdapterConfiguration and display the new settings for each network adapter reflecting any changes that were made.
Listing 24 Staticip-enableex.vbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
On Error Resume Next strComputer = "." arrIPAddresses = Array("192.168.0.12") arrSubnetMasks = Array("255.255.255.0") arrDefaultGateways = Array("192.168.0.1") arrGatewayCostMetrics = Array(1) ' uint16 arrDNSServers = Array("192.168.0.1") strWINSPrimaryServer = "192.168.0.1" strWINSSecondaryServer = "192.168.0.2" intReboot = 0 Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") WScript.Echo VbCrLf & "Host Name: " & strComputer WScript.Echo VbCrLf & "Settings before:" For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & _ " Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf If objNicConfig.DHCPEnabled Then WScript.Echo " Disabling DHCP, enabling static IP ..." intStaticReturn = objNicConfig.EnableStatic(arrIPAddresses, arrSubnetMasks) If intStaticReturn = 0 Then WScript.Echo " DHCP disabled, static IP address enabled." Set objNicChanged = objWMIService.Get _ ("Win32_NetworkAdapterConfiguration.Index=" & objNicConfig.Index) intGatewaysReturn = objNicChanged.SetGateways(arrDefaultGateways, _ arrGatewayCostMetrics) If intGatewaysReturn <> 0 Then WScript.Echo " Unable to assign default gateways." Else WScript.Echo " Assigned new default gateways." End If intDNSServers = objNicChanged.SetDNSServerSearchOrder(arrDNSServers) If intDNSServers <> 0 Then WScript.Echo " Unable to assign DNS servers." Else WScript.Echo " Assigned new DNS servers." End If intWINSServers = objNicConfig.SetWINSServer(strWINSPrimaryServer, _ strWINSSecondaryServer) If intWINSServers <> 0 Then WScript.Echo " Unable to assign WINS servers." Else WScript.Echo " Assigned new WINS servers." End If ElseIf intStaticReturn = 1 Then intReboot = intReboot + 1 WScript.Echo " DHCP disabled, static IP address enabled. " & _ VbCrLf & "Reboot required." Else WScript.Echo " Unable to enable static IP address." End If Else WScript.Echo " Static IP address already enabled." End If Next If (intReboot > 0) Then WScript.Echo VbCrLf & "You must reboot this machine before changes " & _ "will take effect." WScript.Quit Else Set colNicConfigs = objWMIService.ExecQuery("SELECT * FROM " & _ "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") WScript.Echo VbCrLf & "Settings after" For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & _ " Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf & VbCrLf & _ " DHCP Enabled: " & objNicConfig.DHCPEnabled strIPAddresses = "" If Not IsNull(objNicConfig.IPAddress) Then For Each strIPAddress In objNicConfig.IPAddress strIPAddresses = strIPAddresses & VbCrLf & _ " " & strIPAddress Next End If WScript.Echo " IP Addresses: " & strIPAddresses strIPSubnets = "" If Not IsNull(objNicConfig.IPSubnet) Then For Each strIPSubnet In objNicConfig.IPSubnet strIPSubnets = strIPSubnets & VbCrLf & _ " " & strIPSubnet Next End If WScript.Echo " Subnet Masks: " & strIPSubnets strDefaultIPGateways = "" If Not IsNull(objNicConfig.DefaultIPGateway) Then For Each strDefaultIPGateway In objNicConfig.DefaultIPGateway strDefaultIPGateways = strDefaultIPGateways & VbCrLf & _ " " & strDefaultIPGateway Next End If WScript.Echo " Default Gateways: " & strDefaultIPGateways strGatewayCostMetrics = "" If Not IsNull(objNicConfig.GatewayCostMetric) Then For Each strGatewayCostMetric In objNicConfig.GatewayCostMetric strGatewayCostMetrics = strGatewayCostMetrics & VbCrLf & _ " " & strGatewayCostMetric Next End If WScript.Echo " Gateway Cost Metrics: " & strGatewayCostMetrics strDNSServerSearchOrder = "" If Not IsNull(objNicConfig.DNSServerSearchOrder) Then For Each strDNSServer In objNicConfig.DNSServerSearchOrder strDNSServerSearchOrder = strDNSServerSearchOrder & VbCrLf & _ " " & strDNSServer Next End If WScript.Echo " DNS Server Search Order: " & strDNSServerSearchOrder WScript.Echo " WINS Primary Server: " & _ objNicConfig.WINSPrimaryServer WScript.Echo " WINS Secondary Server: " & _ objNicConfig.WINSSecondaryServer Next End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:
C:\scripts>staticip-enableex.vbs
Host Name: .
Settings before:
Network Adapter 1
3Com 3C918 Integrated Fast Ethernet Controller (3C905B-TX Compatible)
Disabling DHCP, enabling static IP ...
DHCP disabled, static IP address enabled.
Reboot required.
You must reboot this machine before changes will take effect.
Scenario: Allocating IP Addresses on a Subnet
This scenario shows how to manage IP addresses for reservations and exclusions. In it, DHCP must be enabled on a subnet or other range of IP addresses, while other clients are assigned static IP addresses from the same pool, so that no IP address is assigned to more than one client. To complete this task, the corresponding changes must also be made on the DHCP server; however, managing the DHCP server is beyond the scope of this paper.
To automate this scenario, one approach is to use two scripts:
Dhcp-enable-subnet.vbs
Enables DHCP for clients with a range of IP addresses set by the administrator. If DHCP is already enabled on a client, the script renews the lease to ensure that client DHCP settings are correct.
Staticip-enable-excl.vbs
Releases DHCP leases on clients for a list of IP addresses to be used for exclusions on the DHCP server. Enables static IP addressing on these clients and assigns an IP address, subnet mask, default gateway and DNS server to each.
The administrator must separately configure the scope on the DHCP server, reserving and excluding the appropriate addresses. The reservations and exclusions on the DHCP server are beyond the scope of this paper.
WMI does not have a DHCP provider; so scripting possibilities on the server are limited. You can use command-line tools like Netsh.exe to perform some tasks on the DHCP server.
Scenario Part One: Configuring DHCP Across a Subnet
To automate the first set of tasks in this scenario, the first script ensures that clients within the correct range of IP addresses (set in the three variables at the beginning of the script) within the scope on the DHCP server are enabled for DHCP. If they are not, the script enables DHCP on them. If DHCP is already enabled on a client, the script renews the DHCP lease to ensure that current settings are retrieved from the server.
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 25 iterates through a range of IP addresses and for each computer, checks each network adapter to see if DHCP is enabled. If it is not, it enables DHCP. You must specify the first part of the IP address and the beginning and ending IP addresses of the range.
Before attempting to make these changes to multiple network hosts, the script performs two error checks, which are considered good practice: the script first pings the host to ensure that it is accessible and then checks for an error in connecting to WMI to ensure that the WMI service is running on the host (it might not be running on older operating systems).
Create variables to specify parameters for the prefix of the IP addresses, and the starting and ending values of the suffix to be postpended to form the full IP addresses.
Use a For loop to iterate through the tasks once for each suffix in the range.
For each suffix (essentially, for each IP address), perform the following tasks.
Concatenate the prefix with the current value of the counter to form an IP address.
Ping this IP address by using the Exec method of the WshShell object to run Ping.exe, with parameters specifying 2 attempts and a time-out of 1 second.
If the host responds to the ping, use a GetObject call to connect to the WMI namespace root\cimv2 on the specified computer, and set the impersonation level to “impersonate.”
Check for an error if binding to WMI.
If a connection has been established with WMI, 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 for which IP is enabled.
For each network adapter configuration in the collection, perform the following tasks.
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 Win32_NetworkAdapterConfiguration.
If the EnableDHCP method returns:
A value of 0, display a message indicating success.
Any other value, display a message indicating failure.
If DHCP is already enabled, display a message to that effect and call the RenewDHCPLease method of Win32_NetworkAdapterConfiguration.
If the RenewDHCPLease method returns:
A value of 0, display a message indicating success.
Any other value, display a message indicating failure.
If an error occurred in binding to WMI, display an error message.
If the host does not respond to the ping, display an error message.
Listing 25 Dhcp-enable-subnet.vbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
On Error Resume Next strSubnetPrefix = "192.168.0." intBeginSubnet = 10 intEndSubnet = 12 For i = intBeginSubnet To intEndSubnet strComputer = strSubnetPrefix & i ' Ping remote computer. If inaccessible, display error message. Set objShell = CreateObject("WScript.Shell") Set objScriptExec = objShell.Exec("ping -n 2 -w 1000 " & strComputer) strPingResults = LCase(objScriptExec.StdOut.ReadAll) If InStr(strPingResults, "reply from") Then WScript.Echo VbCrLf & "Host Name " & strComputer Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") ' Test for success in binding to WMI. If Err = 0 Then arrIPAddresses = Array(strComputer) Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE " & _ "IPEnabled = True") For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & _ VbCrLf & " " & objNicConfig.Description & VbCrLf If Not objNicConfig.DHCPEnabled Then WScript.Echo " Enabling DHCP ..." intEnableReturn = objNicConfig.EnableDHCP If intEnableReturn = 0 Then WScript.Echo VbCrLf & " DHCP enabled." Else WScript.Echo VbCrLf & " Unable to enable DHCP." End If Else WScript.Echo " DHCP already enabled" & VbCrLf & _ " DHCP Server: " & objNicConfig.DHCPServer & _ VbCrLf & " Renewing DHCP lease ..." intRenewReturn = objNicConfig.RenewDHCPLease If intRenewReturn = 0 Then WScript.Echo VbCrLf & " DHCP lease renewed." Else WScript.Echo VbCrLf & " Unable to renew DHCP lease." End If End If Next Else Wscript.Echo " Error: Unable to connect to WMI." Err.Clear End If Else WScript.Echo VbCrLf & "Host Name: " & strComputer & VbCrLf & _ " Unable to connect." End If Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:
C:\scripts>dhcp-enable-subnet.vbs
Host Name 192.168.0.10
Network Adapter 1
3Com 3C918 Integrated Fast Ethernet Controller (3C905B-TX Compatible)
DHCP already enabled
DHCP Server: 192.168.0.1
Renewing DHCP lease ...
DHCP lease renewed.
Host Name 192.168.0.11
Network Adapter 1
3Com 3C918 Integrated Fast Ethernet Controller (3C905B-TX Compatible)
DHCP already enabled
DHCP Server: 192.168.0.1
Renewing DHCP lease ...
DHCP lease renewed.
Host Name 192.168.0.12
Unable to connect.
Scenario Part Two: Enabling Static IP Addresses on Exclusions
To automate the second set of tasks in this scenario, the second script releases DHCP leases and enables static IP addresses on the clients that are excluded from the subnet. After successfully completing this task, the script then assigns the clients default gateways and DNS servers to allow them to reconnect to the network.
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 26 iterates through a range of host names and for each computer, checks each network adapter to see if DHCP is enabled. If DHCP is enabled, the script releases the lease and then assigns a static IP address and subnet mask. If static IP addressing is successfully enabled, assign a default gateway and DNS server to the network adapter.
Create variables to specify all necessary parameters. These include the list of computers against which to run, and the IP addresses and other settings to be assigned to each when static IP addressing is enabled.
Initialize to 0 a loop counter, which is used to select the correct IP address from the array for each computer.
Iterate through each host name in the list of computers on which to configure static IP addressing.
Ping this host name by using the Exec method of the WshShell object to run Ping.exe, with parameters specifying two attempts and a time-out of 1 second.
If the host responds to the ping, select the IP address from the array whose index is equal to the current value of the loop counter. Assign this IP address to a new one-element array that will be assigned to this host when static IP addressing is enabled. Remember that the value of the IPAddress property is an array of strings.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified computer, and set the impersonation level to “impersonate.”
Check for an error if binding to WMI.
If a connection has been established with WMI, 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 for which IP is enabled.
For each network adapter configuration in the collection, perform the following tasks.
Display the index number and description of the network adapter.
Check whether DHCP is already enabled.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified 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 computer for which IP is enabled.
For each network adapter configuration in the collection, perform the following tasks.
Call the ReleaseDHCPLease method of Win32_NetworkAdapterConfiguration to release the DHCP lease, and display a success or error message depending on the return value.
Call the EnableStatic method of Win32_NetworkAdapterConfiguration, passing it the one-element array of IP addresses for this host and the one-element array of subnet masks (the latter is the same for all hosts).
If the EnableStatic method succeeds, call the Get method to get a new reference to the current instance of Win32_NetworkAdapterConfiguration. This refreshes the properties of this object so that further changes can be made.
Call the SetGateways and SetDNSServerSearchOrder methods of Win32_NetworkAdapterConfiguration, passing them the appropriate variables as parameters.
Check the return value of both methods and display a success or failure message for each.
If a static IP address cannot be assigned, display an error message.
If DHCP is not enabled, display a message that static IP addressing is already enabled.
Requery the Win32_NetworkAdapterConfiguration class for IP-enabled adapters to retrieve any new values reflecting the changes just made, and display the relevant properties.
If an error occurred in binding to WMI, display an error message.
If the host does not respond to the ping, display an error message.
Increment the loop counter used to select the IP address from the array.
Listing 26 Staticip-enable-excl.vbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
On Error Resume Next arrComputers = Array("client1", "client2", "client3") ' There must be one IP in arrStaticIPs for each host in arrComputers. arrStaticIPs = Array("192.168.0.240","192.168.0.243","192.168.0.250") arrSubnetMasks = Array("255.255.255.0") arrDefaultGateways = Array("192.168.0.1") arrGatewayCostMetrics = Array(1) arrDNSServers = Array("192.168.0.1") intCount = 0 For Each strComputer In arrComputers ' Ping remote computer. If inaccessible, display error message. Set objShell = CreateObject("WScript.Shell") Set objScriptExec = objShell.Exec("ping -n 2 -w 1000 " & strComputer) strPingResults = LCase(objScriptExec.StdOut.ReadAll) If InStr(strPingResults, "reply from") Then WScript.Echo VbCrLf & "Host Name: " & strComputer arrIPAddresses = Array(arrStaticIPs(intCount)) Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & _ "\root\cimv2") ' Test for success in binding to WMI. If Err = 0 Then Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE " & _ "IPEnabled = True") For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & " Network Adapter " & _ objNicConfig.Index & VbCrLf & " " & _ objNicConfig.Description & VbCrLf If objNicConfig.DHCPEnabled Then intStaticReturn = objNicConfig.EnableStatic(arrIPAddresses, _ arrSubnetMasks) If intStaticReturn = 0 Then WScript.Echo " DHCP disabled, static IP address enabled." Set objNicChanged = objWMIService.Get _ ("Win32_NetworkAdapterConfiguration.Index=" & objNicConfig.Index) intGatewaysReturn = objNicChanged.SetGateways _ (arrDefaultGateways, arrGatewayCostMetrics) If intGatewaysReturn = 0 Then WScript.Echo " Assigned new default gateways." Else WScript.Echo " Unable to assign default gateways." End If intDNSServersReturn = objNicChanged.SetDNSServerSearchOrder _ (arrDNSServers) If intDNSServersReturn = 0 Then WScript.Echo " Assigned new DNS servers." Else WScript.Echo " Unable to assign DNS servers." End If Else WScript.Echo " Unable to enable static IP address." End If Else WScript.Echo " Static IP address already enabled." End If Next Set colNicConfigs = objWMIService.ExecQuery("SELECT * FROM " & _ "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & _ " Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf & _ " DHCP Enabled: " & objNicConfig.DHCPEnabled strIPAddresses = "" If Not IsNull(objNicConfig.IPAddress) Then For Each strIPAddress In objNicConfig.IPAddress strIPAddresses = strIPAddresses & VbCrLf & _ " " & strIPAddress Next End If WScript.Echo " IP Addresses: " & strIPAddresses strIPSubnets = "" If Not IsNull(objNicConfig.IPSubnet) Then For Each strIPSubnet In objNicConfig.IPSubnet strIPSubnets = strIPSubnets & VbCrLf & _ " " & strIPSubnet Next End If WScript.Echo " Subnet Masks: " & strIPSubnets strDefaultIPGateways = "" If Not IsNull(objNicConfig.DefaultIPGateway) Then For Each strDefaultIPGateway In objNicConfig.DefaultIPGateway strDefaultIPGateways = strDefaultIPGateways & VbCrLf & _ " " & strDefaultIPGateway Next End If WScript.Echo " Default Gateways: " & strDefaultIPGateways strGatewayCostMetrics = "" If Not IsNull(objNicConfig.GatewayCostMetric) Then For Each strGatewayCostMetric In objNicConfig.GatewayCostMetric strGatewayCostMetrics = strGatewayCostMetrics & VbCrLf & _ " " & strGatewayCostMetric Next End If strDNSServerSearchOrder = "" WScript.Echo " Gateway Cost Metrics: " & strGatewayCostMetrics If Not IsNull(objNicConfig.DNSServerSearchOrder) Then For Each strDNSServer In objNicConfig.DNSServerSearchOrder strDNSServerSearchOrder = strDNSServerSearchOrder & VbCrLf & _ " " & strDNSServer Next End If WScript.Echo " DNS Server Search Order: " & strDNSServerSearchOrder Next Else Wscript.Echo " Error: Unable to connect to WMI." Err.Clear End If Else WScript.Echo VbCrLf & "Host Name: " & strComputer & VbCrLf & _ " Unable to connect." & VbCrLf End If intCount = intCount + 1 Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:
C:\scripts>staticip-enable-excl.vbs
Host Name: client1
Unable to connect.
Host Name: client2
Network Adapter 1
3Com 3C918 Integrated Fast Ethernet Controller (3C905B-TX Compatible)
Releasing DHCPlease ...
DHCP lease released.
Disabling DHCP, enabling static IP address ...
DHCP disabled, static IP address enabled.
Assigned new default gateways.
Assigned new DNS servers.
Network Adapter 1
3Com 3C918 Integrated Fast Ethernet Controller (3C905B-TX Compatible)
DHCP Enabled: False
IP Addresses:
192.168.0.243
Subnet Masks:
255.255.255.0
Default Gateways:
192.168.0.1
Gateway Cost Metrics:
20
DNS Server Search Order:
192.168.0.1
Host Name: client3
Error: Unable to connect to WMI.
Scenario: Switching Between a Static IP Address and DHCP
In this scenario, a "road warrior" needs to connect her laptop to a corporate network in different branch offices. In some, the network requires that clients use DHCP and in others, the computer must use a static address (along with a subnet mask, default gateway, DNS server, and WINS server). To run this script, the user types the name of the script followed by a space and the name of the current office where the computer is located. According to the location, the script assigns one or the other address allocation method: static in Miami and Dogpatch; DHCP in Seattle and Boston.
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 27 enables the user to change between DHCP and static IP addressing on a portable computer by using a command-line argument that represents the current location entered by the user. The script is broken down into subroutines that make it more modular and easier to read, debug, and modify.
This script uses the WScript.Arguments property, which is part of Windows Script Host. The script returns a collection of all the arguments typed on the command line after the name of the script. For more information about using this property, see "Working with Command-Line Arguments" in the "WSH Primer" section of the Windows 2000 Scripting Guide at https://go.microsoft.com/fwlink/?LinkId=29994.
Use the WScript.Arguments collection to retrieve the command-line argument entered after the script name.
This script takes only one argument: the name of the office where the user wants to connect to the local area network. Any other arguments are ignored.
Assign the first argument, colArgs(0), to the strOffice variable.
Use a Select Case statement to assign a Boolean value, True or False, to blnDHCP depending on the name of the branch office entered as a command-line argument.
If the argument is not one of the four valid names, the script displays an error message and exits.
Use a GetObject call to connect to the WMI namespace root\cimv2 on the local 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 computer for which IP is enabled.
If the office whose name was passed as an argument uses DHCP, call the SetDHCP subroutine.
If the office does not use DHCP, call the SetStaticIP subroutine.
The SetDHCP subroutine checks the DHCPEnabled property and if DHCP is not enabled, calls the EnableDHCP method. If DHCP is already enabled, SetDHCP displays a message to that effect and the IP address of the DHCP server.
Before ending, SetDHCP calls the GetSettings subroutine.
If DHCP is already enabled, you might want to add code to the subroutine that renews the lease. Dhcp-enable-subnet.vbs, in the previous scenario, provides an example of how to do this. Although the DHCP client should find the local DHCP server and get local configuration, renewing the lease can expedite this process in some network environments.
The SetStaticIP subroutine begins with hard-coded variables that assign the settings necessary for static IP addressing (a more complex script could obtain these settings from an external source). SetStaticIP then checks the DHCPEnabled property and if DHCP is enabled, calls the EnableStatic method. If EnableStatic succeeds, SetStaticIP then calls the SetGateways and SetDNSServerSearchOrder methods to complete the static IP configuration.
If DHCP is already enabled, SetDHCP displays a message to that effect and the IP address of the DHCP server.
Before ending, SetStaticIP calls the GetSettings subroutine.
The GetSettings subroutine, which is called by both SetDHCP and SetStaticIP, requeries Win32_NetworkAdapterConfiguration to retrieve any changes made by the previous subroutines. GetSettings then displays the relevant IP address allocation settings that are currently on the computer.
Listing 27 Dhcp-staticip-switch.vbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
On Error Resume Next ' Get argument to find out what office we're in and set a switch based on it. Set colArgs = WScript.Arguments strOffice = LCase(colArgs(0)) Select Case strOffice Case "boston" blnDHCP = True Case "miami" blnDHCP = False Case "seattle" blnDHCP = True Case "dogpatch" blnDHCP = False Case Else WScript.Echo "Please enter the script name followed by a " & _ "space and the name of a branch office." & _ VbCrLf & "Valid names are: Boston, Miami, Seattle and Dogpatch." _ : WScript.Quit End Select Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set colNicConfigs = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") ' If the office uses DHCP, call SetDHCP. If blnDHCP = True Then WScript.Echo "You are in the " & colArgs(0) & " branch office." & _ VbCrLf & "Enabling DHCP on all network adapters ..." SetDHCP ' If the office uses static IP, call SetStaticIP. Else WScript.Echo "You are in the " & colArgs(0) & " branch office." & _ VbCrLf & "Enabling static IP addressing on all network adapters ..." SetStaticIP End If '****************************************************************************** Sub SetDHCP For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & "Network Adapter " & objNicConfig.Index & _ VbCrLf & " " & objNicConfig.Description & VbCrLf If Not objNicConfig.DHCPEnabled Then WScript.Echo " Attempting to enable DHCP ..." intReturn = objNicConfig.EnableDHCP If intReturn = 0 Then WScript.Echo " DHCP enabled." Else WScript.Echo " Unable to enable DHCP." End If Err.Clear Else WScript.Echo " DHCP already enabled" & VbCrLf & _ " DHCP Server: " & objNicConfig.DHCPServer Err.Clear End If Next GetSettings End Sub '****************************************************************************** Sub SetStaticIP arrIPAddresses = Array("192.168.0.12") arrSubnetMasks = Array("255.255.255.0") arrDefaultGateways = Array("192.168.0.1") arrGatewayCostMetrics = Array(1) arrDNSServers = Array("192.168.0.1") For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & "Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf If objNicConfig.DHCPEnabled Then WScript.Echo " Attempting to disable DHCP and enable static IP ..." intStaticReturn = objNicConfig.EnableStatic(arrIPAddresses, arrSubnetMasks) If intStaticReturn = 0 Then WScript.Echo " DHCP disabled, static IP address enabled." Set objNicChanged = objWMIService.Get _ ("Win32_NetworkAdapterConfiguration.Index=" & objNicConfig.Index) intGatewaysReturn = objNicChanged.SetGateways(arrDefaultGateways, _ arrGatewayCostMetrics) intDNSServers = objNicChanged.SetDNSServerSearchOrder(arrDNSServers) If intGatewaysReturn = 0 Then WScript.Echo " Assigned new default gateways." Else WScript.Echo " Unable to assign default gateways." End If If intDNSServers = 0 Then WScript.Echo " Assigned new DNS servers." Else WScript.Echo " Unable to assign DNS servers." End If Err.Clear Else WScript.Echo " Unable to enable static IP address." Err.Clear End If Else WScript.Echo " Static IP address already enabled." End If Next GetSettings End Sub '****************************************************************************** Sub GetSettings Set colNicConfigs = objWMIService.ExecQuery("SELECT * FROM " & _ "Win32_NetworkAdapterConfiguration WHERE IPEnabled = True") WScript.Echo VbCrLf & "Settings after operation:" For Each objNicConfig In colNicConfigs WScript.Echo VbCrLf & _ "Network Adapter " & objNicConfig.Index & VbCrLf & _ " " & objNicConfig.Description & VbCrLf & VbCrLf & _ " DHCP Enabled: " & objNicConfig.DHCPEnabled strIPAddresses = "" If Not IsNull(objNicConfig.IPAddress) Then For Each strIPAddress In objNicConfig.IPAddress strIPAddresses = strIPAddresses & VbCrLf & _ " " & strIPAddress Next End If WScript.Echo " IP Addresses: " & strIPAddresses strIPSubnets = "" If Not IsNull(objNicConfig.IPSubnet) Then For Each strIPSubnet In objNicConfig.IPSubnet strIPSubnets = strIPSubnets & VbCrLf & _ " " & strIPSubnet Next End If WScript.Echo " Subnet Masks: " & strIPSubnets strDefaultIPGateways = "" If Not IsNull(objNicConfig.DefaultIPGateway) Then For Each strDefaultIPGateway In objNicConfig.DefaultIPGateway strDefaultIPGateways = strDefaultIPGateways & VbCrLf & _ " " & strDefaultIPGateway Next End If WScript.Echo " Default Gateways: " & strDefaultIPGateways strGatewayCostMetrics = "" If Not IsNull(objNicConfig.GatewayCostMetric) Then For Each strGatewayCostMetric In objNicConfig.GatewayCostMetric strGatewayCostMetrics = strGatewayCostMetrics & VbCrLf & _ " " & strGatewayCostMetric Next End If WScript.Echo " Gateway Cost Metrics: " & strGatewayCostMetrics strDNSServerSearchOrder = "" If Not IsNull(objNicConfig.DNSServerSearchOrder) Then For Each strDNSServer In objNicConfig.DNSServerSearchOrder strDNSServerSearchOrder = strDNSServerSearchOrder & VbCrLf & _ " " & strDNSServer Next End If WScript.Echo " DNS Server Search Order: " & strDNSServerSearchOrder Next End Sub
When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:
C:\scripts>dhcp-staticip-switch.vbs Boston
You are in the Boston branch office.
Enabling DHCP on all network adapters ...
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packet
Scheduler Miniport
DHCP already enabled
DHCP Server: 192.168.0.1
Settings after operation:
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packet
Scheduler Miniport
DHCP Enabled: True
IP Addresses:
192.168.0.21
Subnet Masks:
255.255.255.0
Default Gateways:
192.168.0.1
Gateway Cost Metrics:
20
DNS Server Search Order:
192.168.0.1
C:\scripts\netcli>dhcp-staticip-switch.vbs Miami
You are in the Miami branch office.
Enabling static IP addressing on all network adapters ...
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packet
Scheduler Miniport
Attempting to disable DHCP and enable static IP ...
DHCP disabled, static IP address enabled.
Assigned new default gateways.
Assigned new DNS servers.
Settings after operation:
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packet
Scheduler Miniport
DHCP Enabled: False
IP Addresses:
192.168.0.12
Subnet Masks:
255.255.255.0
Default Gateways:
192.168.0.1
Gateway Cost Metrics:
1
DNS Server Search Order:
192.168.0.1
Tools for IP Address Allocation on Clients
Table 11 outlines the available Windows tools to use for scripting IP address allocation on clients.
Table 11 Tools for IP Address Allocation on Clients
Technology
Tool
Where Available
Command-line tools
Dhcploc.exe: DHCP Server Locator Utility
Windows Server 2003 Support Tools
Command-line tools
Enabledhcp.vbs
Windows 2000 Resource Kit
Command-line tools
Netsh.exe
Windows operating systems1
WSH
None
WMI
Win32_NetworkAdapterConfiguration
1 Windows 2000, Windows XP, and Windows Server 2003. May also be present on other versions of Windows.
Table 12 outlines the available registry keys to use for scripting IP address allocation on clients.
Caution
Incorrectly editing the registry may severely damage your system. Before making changes to the registry, you should back up any valued data on the computer.Table 12 Registry Subkeys Related to Scripting IP Address Allocation on Clients
Registry Subkeys
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dhcp\Parameters