自动配置客户端上的 TCP/IP 网络

第 4 部分:使用脚本管理客户端上的 IP 地址分配

发布日期: 2004年11月16日

TCP/IP 联网的核心工作是 IP 地址分配。如果您的网络使用动态主机配置协议 (DHCP),则说明您已采用了一种自动化方式来管理这项关键的功能。

在 TCP/IP 联网技术发展的早期,管理员以手动方式来分配 IP 地址。随着网络规模的扩大和复杂性的提高,这种做法就行不通了。早期为使该功能实现自动化而采取的技术(例如,逆向地址解析协议 (RARP) 和 Bootstrap 协议 (BOOTP))仍然需要进行大量的手动配置。后来开发了 DHCP 以取代早期的那些技术,并将其功能扩展为一个客户端/服务器协议,该协议能够管理 IP 地址池和相关的客户端配置参数,同时大大减少了所需的管理干预操作。

现在,无论规模大小,大多数网络都将 DHCP 作为自动管理 IP 地址配置的默认方式。不过,即使您的网络使用 DHCP,在某些情况下(例如,在设置排除时)您可能仍然需要使用静态 IP 地址。此外,一些较小或较早的网络可能只使用静态 IP 地址。

DHCP 服务器和客户端还与其他 TCP/IP 组件进行各种方式的交互。例如,当您使用 DNS 动态更新时,DHCP 客户端和服务器会将 IP 地址更改更新到 DNS 服务器中,以确保在中止和续订 IP 地址租约时,名称解析仍然正确无误。

这里,与大多数 TCP/IP 设置一样,您可以使用 Windows 界面在本地计算机上手动进行更改。例如,如图 9 所示,您可以在“高级 TCP/IP 设置”对话框的“IP 设置”选项卡上配置 DHCP 设置。

图 9   使用 Windows 界面配置 DHCP 设置

图 9   使用 Windows 界面配置 DHCP 设置
查看大图

正如前面所提到的,您还可以使用命令行工具 Ipconfig.exe 来检索 DHCP 客户端设置,中止和续订租约以及执行其他 DHCP 客户端任务。对于远程客户端和多个客户端以及可能发生手动错误的复杂本地任务,使用脚本可能是一种更为有效的方法。

本节讨论如何同时使用 DHCP 和静态寻址,通过脚本来管理 IP 地址分配。虽然在某些情况下,在客户端上进行更改时也需要在 DHCP 服务器上进行更改,但是本文只介绍如何配置客户端。DHCP 服务器的管理不在本文的讨论范围之内。

本页内容
管理客户端上的 DHCP管理客户端上的 DHCP
管理静态 IP 地址管理静态 IP 地址
方案:分配子网上的 IP 地址方案:分配子网上的 IP 地址
方案:在静态 IP 地址和 DHCP 之间切换方案:在静态 IP 地址和 DHCP 之间切换
用于管理客户端上的 IP 地址分配的工具用于管理客户端上的 IP 地址分配的工具

管理客户端上的 DHCP

虽然 DHCP 已经是一种自动化方式,但是使用脚本可以帮助您自动配置一组客户端以利用 DHCP。通过 WMI 类 Win32_NetworkAdapterConfiguration 提供的属性和方法,您可以枚举 DHCP 设置,启用或禁用 DHCP,以及续订或中止租约。

表 9 说明了可用于 IP 地址分配的 Win32_NetworkAdapterConfiguration 属性。

表 9   Win32_NetworkAdapterConfiguration IP 地址分配属性

属性类型说明

DefaultIPGateway

字符串数组

计算机系统使用的默认网关的 IP 地址数组。

DHCPEnabled

布尔

如果是 True,DHCP 服务器会在建立网络连接时自动为计算机系统分配一个 IP 地址。

DHCPLeaseExpires

datetime

DHCP 服务器为计算机分配的租用 IP 地址的到期日期和时间。

DHCPLeaseObtained

datetime

DHCP 服务器为计算机分配的 IP 地址获得租约的日期和时间。

DHCPServer

字符串

DHCP 服务器的 IP 地址。

GatewayCostMetric

Uint16

用于计算最快、最可靠或最廉价路由的整数成本跃点数值(从 1 到 9999)数组。这个参数与 DefaultIPGateway 属性之间存在一一对应关系。

IPConnectionMetric

(Windows XP 的新增属性)

Uint32

绑定了 IP 的适配器的已配置路由的使用成本;对于 IP 路由表中的路由来说,这是一个加权值。如果在 IP 路由表中有多个指向目标计算机的路由,将使用跃点数最少的路由。默认值是 1。

IPAddress

字符串

与当前网络适配器相关的所有 IP 地址构成的数组。

IPSubnet

字符串

与当前网络适配器相关的所有子网掩码构成的数组。

上表中的所有属性都是只读的。类型 uint16 和 uint32 是由强类型编程语言使用的无符号整数类型;VBScript 可将它们有效地作为整数进行处理。

表 10 描述了可用于 IP 地址分配的 Win32_NetworkAdapterConfiguration 方法。

表 10   Win32_NetworkAdapterConfiguration IP 地址分配方法

方法参数说明

EnableDHCP

为使用这个网络适配器的服务启用 DHCP。DHCP 允许动态分配 IP 地址。

EnableStatic

IPAddress – 字符串数组

SubnetMask – 字符串数组

为目标网络适配器启用静态 TCP/IP 寻址。这样便会对此网络适配器禁用 DHCP。

ReleaseDHCPLease

释放已绑定到启用了 DHCP 的特定网络适配器的 IP 地址。

警告  如果在本地计算机上启用 DHCP,该选项会对这个特定的网络适配器禁用 TCP/IP。如果您没有访问目标系统的其他路径(即另一个绑定 TCP/IP 的网络适配器),所有 TCP/IP 通信都会中断。

ReleaseDHCPLeaseAll

静态方法。释放已绑定到所有启用了 DHCP 的网络适配器的 IP 地址。

警告  如果在本地计算机上启用 DHCP,此选项将终止所有的 DHCP TCP/IP 连接。

RenewDHCPLease

续订启用了 DHCP 的特定网络适配器上的 IP 地址。DHCP 服务器分配的 IP 地址的租约有一个截止日期;如果客户端打算继续使用分配的 IP 地址,就必须进行续订。

RenewDHCPLeaseAll

静态方法。续订所有启用了 DHCP 的网络适配器的 IP 地址。DHCP 服务器分配的 IP 地址的租约有一个截止日期;如果客户端打算继续使用分配的 IP 地址,就必须进行续订。

SetGateways

DefaultIPGateway – 字符串数组

GatewayCostMetric – unit16

指定一个网关列表,这些网关用于将数据包路由到该网络适配器连接的子网以外的子网。该方法仅在网络适配器处于静态 IP 模式时才有效。

上表中的所有方法都返回一个正整数:

0 表示成功完成。

1 表示成功完成,并需要重新启动。

大于 1 的数字表示出现了某种问题,方法无法完成。WMI SDK 列出了这些方法的返回值的含义。

显示 DHCP 客户端信息

如果您在使用诸如 DHCP 之类的技术,使用脚本的第一步通常是确定与它相关的设置的当前配置。这也是本节及后面各节所用的一个步骤。

Win32_NetworkAdapterConfiguration 提供基于每个适配器的属性,这些属性显示是否启用了 DHCP;显示 DHCP 服务器的 IP 地址;显示租约获得和到期的日期和时间;显示客户端 IP 地址和子网掩码(各网络适配器可以具有一个以上的属性)。

因为 WMI 返回的日期和时间的格式可读性较差,所以在显示租约日期和时间时,需要将 WMI 日期和时间格式转换为对用户更友好的格式。

下面的脚本使用 Win32_NetworkAdapterConfiguration 的以下属性来显示网络客户端的 IP 地址分配设置:DHCPEnabled、DHCPServer、DHCPLeaseObtained、DHCPLeaseExpires、IPAddress 和 IPSubnet。只有在启用了 DHCP 时,此脚本才显示 DHCPServer、DHCPLeaseObtained 和 DHCPLeaseExpires 的设置。

此脚本不是使用 WSH WScript.Echo 方法直接显示设置,而是将设置收集起来并分配给一个字符串,然后再进行显示。接着,在使用 If ...Then 语句验证 DHCPEnabled 为 True 后,此脚本将显示从属设置。

由 Dhcpsettings.vbs、DHCPLeaseObtained 和 DHCPLeaseExpires 显示的设置中有两个是作为 DATETIME 值返回的。如果您显示原始值,它看上去就像下面这种形式:

20021201000230.000000+000

前四个数字代表年,随后的两个数字代表月,再后面的两个数字代表日,然后是小时、分、秒。您可以判断出它的含义,不过,得花点时间。

Windows XP 和 Windows Server 2003 向 WMI 脚本 API 中添加了一个新的 SWbemDateTime 对象。如果所有客户端运行的都是 Windows XP 和 Windows Server 2003,则可以使用该对象来更轻松地分析和转换 datetime 值。

但是,如果并非所有的网络主机都运行 Windows XP 或 Windows Server 2003,则可以采用一种更方便、更简单的解决方案:即使用 VBScript 的字符串处理功能,将 datetime 值分析成一种易读的格式。

在此脚本中,为了将 datetime 值转换为可读性较高的格式,Dhcpsettings 调用了函数 WMIDateToString(),并将 datetime 值作为参数传递给该函数。该函数使用 VBScript 内置的 Mid() 和 Left() 字符串函数来转换值。然后,它调用 VBScript CDate() 函数将变量值(所有 VBScript 变量的类型)强制转换为“Date”子类型,并将转换后的日期返回给脚本的主体。

有关 WMI DATETIME 格式的更多信息,请参见下文中的“使用 WMI 在一台计算机上设置时间”。

脚本步骤

列表 19 显示了计算机上的每个网络适配器配置的 DHCP 设置。

1.

创建一个变量,并将计算机的名称分配给它。对于本地计算机,将“.”指定为计算机的名称即可。若要远程运行这个脚本,请指定网络上一台您拥有管理权限且可访问的远程计算机的名称。名称的形式可以是主机名,也可以是 IP 地址。

2.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

3.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

4.

对于集合中的每个网络适配器配置,请执行以下任务。

5.

对 objWMIService 调用 Get 方法以获得对 Win32_NetworkAdapter 实例的对象引用,该实例的 DeviceID 属性相当于 Win32_NetworkAdapterConfiguration 的当前实例的 Index 属性。

6.

获取 Win32_NetworkAdapterConfiguration 的 DNSHostName 属性的值,并将该值分配给一个变量。

7.

获取 Win32_NetworkAdapter 的 NetConnectionID 属性的值,并将该值分配给一个变量。如果此操作引发了一条错误,请改用 Win32_NetworkAdapterConfiguration 的 Index 属性。

8.

获取 Win32_NetworkAdapterConfiguration 的 DHCPEnabled 属性,并将该属性分配给一个变量。

9.

如果 DHCPEnabled 属性为 True(意味着当前的网络适配器上已启用了 DHCP),请获取与 IP 地址分配相关的其他属性,并将获取的属性分配给变量。

10.

对于 Win32_NetworkAdapterConfiguration 的 DHCPLeaseObtained 和 DHCPLeaseExpires 这两个属性,请将它们的值作为参数传递给 WMIDateToString 函数。该函数可将这两个属性返回的 DATETIME 格式转换为可读性较高的字符串。

11.

将包含带有说明性标签的属性值的变量连接成一个长字符串,然后使用 WScript.Echo 显示该字符串。

列表 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
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
  strDNSHostName = objNicConfig.DNSHostName
  strIndex = objNicConfig.Index
  strDescription = objNicConfig.Description
  blnDHCPEnabled = objNicConfig.DHCPEnabled
  If blnDHCPEnabled Then
    strDHCPServer = objNicConfig.DHCPServer
    dtmRawLeaseObtainedDate = objNicConfig.DHCPLeaseObtained
    strDHCPLeaseObtained = WMIDateToString(dtmRawLeaseObtainedDate)
    dtmRawLeaseExpiresDate = objNicConfig.DHCPLeaseExpires
    strDHCPLeaseExpires = WMIDateToString(dtmRawLeaseExpiresDate)
  End If
  strDHCPSettings = strDHCPSettings & VbCrLf & VbCrLf & _
   "  Network Adapter " & strIndex & VbCrLf & _
   "    " & strDescription & VbCrLf & VbCrLf & _
   "    DHCP Enabled:        " & blnDHCPEnabled
  If blnDHCPEnabled Then
    strDHCPSettings = strDHCPSettings & VbCrLf & _
     "    DHCP Server:         " & strDHCPServer & VbCrLf & _
     "    DHCP Lease Obtained: " & strDHCPLeaseObtained & VbCrLf & _
     "    DHCP Lease Expires:  " & strDHCPLeaseExpires
  End If
Next
 
WScript.Echo VbCrLf & "DHCP Settings" & VbCrLf & VbCrLf & _
 "Host Name: " & strDNSHostName & strDHCPSettings
 
'******************************************************************************
 
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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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

在客户端上启用 DHCP

如果必须将一个远程客户端或一组远程客户端组从使用静态 IP 地址转换为自动获取 IP 地址,那么,花些时间将客户端上的 DHCP 配置实现自动化是值得的。根据 DHCP 和 DNS 服务器的配置方式,启用 DHCP 可能还会使客户端从 DHCP 服务器获取 DNS 服务器地址和默认网关地址。

下面的脚本旨在说明如何使用 EnableDHCP,它是 Win32_NetworkAdapterConfiguration 的一个方法,用于为客户端的网络适配器上的服务启用 DHCP。该方法不带任何参数。对于拥有一个以上网络适配器的客户端(例如双穴计算机),您可以将脚本改编为只启用某个适配器。

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 20 为计算机上的各个网络适配器配置启用 DHCP。

1.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

2.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

3.

对于集合中的每个网络适配器配置,请执行以下任务。

4.

显示网络适配器的索引号和说明。

5.

检查是否已经启用了 DHCP。

6.

如果 DHCP 未启用,请调用 Win32_NetworkAdapterConfiguration 的 EnableDHCP 方法。

7.

如果 EnableDHCP 方法返回:

值 0,则显示一条表示成功的消息。

任何非 0 值,则显示一条表示失败的消息。

8.

如果 DHCP 已经启用,则显示一条消息说明这种状况,并显示 DHCP 服务器的 IP 地址。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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.

管理 DHCP 租约

DHCP 分配的 IP 地址通常只在指定的时段内有效。这种临时地址分配叫做租约。DHCP 服务器的管理员可以配置租约的默认期限,具体情况取决于您添加或删除网络客户端的频率,或者子网上的地址数和客户端数,等等。

DHCP 客户端和服务器能够在租约到期之前自动重新协商租约。您也可以手动或以编程方式中止或续订租约。例如,命令行工具 Ipconfig.exe 就为此目的提供了一些参数。

Win32_NetworkAdapterConfiguration 提供了以下四种基于每个适配器的方法,您可以用这些方法来管理其实例的 DHCP 租约:ReleaseDHCPLease、ReleaseDHCPLeaseAll、RenewDHCPLease 和 RenewDHCPLeaseAll。您也可以通过循环访问网络适配器配置集合并对各个租约使用 ReleaseDHCPLease 或 RenewDHCPLease 来中止或续订所有的租约。

中止 DHCP 租约

如果中止网络适配器的 DHCP 租约,便会断开该适配器与网络的连接,并释放其 IP 地址以便再将地址分配给其他主机。ipconfig.exe /release 命令可对所有网络适配器或特定适配器执行此任务。

在以下情况下,您可能需要中止客户端上的 DHCP 租约:即当您保留 DHCP 服务器上的某个作用域(一组 IP 地址)来进行永久租约分配时。该作用域内保留的某些地址可能已经被现有客户端使用,因而该作用域内将不包含这些地址。通过将一个 IP 地址添加到 DHCP 服务器上的某个作用域,并不能使当前拥有该地址的客户端自动释放该地址。

下面的脚本介绍了一种解决该问题的方法。它循环访问网络适配器配置集合,并使用 ReleaseDHCPLease 方法来中止各个配置的租约。通过更改下面一行代码,可以轻松地将此脚本改编为中止远程客户端上的租约:

strComputer = "."

将本地计算机(“.”)替换成那个为了保留而需要释放的 IP 地址。例如:

strComputer = "192.168.0.135"

与所有远程 WMI 操作一样,用户必须拥有远程计算机的相应管理权限。

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 21 首先显示各个网络适配器的 DHCP 设置。然后检查各个网络适配器以查看是否启用了 DHCP;如果启用了,则中止 DHCP 租约。

1.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

2.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

3.

显示标签“Settings before releasing lease”。

4.

对于集合中的每个网络适配器配置,请执行以下步骤。

5.

显示索引号、说明以及各个适配器是否启用了 DHCP。

6.

如果启用了 DHCP,则检索 DHCP 租约的获取日期和到期日期,并调用 WMIDateToString 函数将这两个日期转换成易读的格式。

显示 DHCP 服务器的 IP 地址和租约日期。

7.

调用 Win32_NetworkAdapterConfiguration 的 ReleaseDHCPLease 方法,然后等待 5 秒钟让中止过程完成。

important.gif  重要说明
如果客户端使用 DHCP 来获取 IP 地址,则中止租约可能导致客户端断开与网络的连接。

8.

如果 ReleaseDHCPLease 方法返回:

值 0,则显示一条消息,指出租约已中止。

值 1,则显示一条消息,指出租约已中止,并且必须重新启动计算机。

大于 1 的值,则显示一条消息,指出租约无法中止。

9.

再次查询 Win32_NetworkAdapterConfiguration 类,并再次只筛选启用了 IP 的适配器。这次重新查询是有必要的,因为每次查询都返回一个设置快照(在运行查询时找到的设置),而在设置随后发生更改时,查询并不能自动更新。

10.

重新显示早先显示的 DHCP 相关设置。

11.

WMIDateToString 函数接受 WMI DATETIME 格式的值,并将它转换成一个字符串,以便按可读性更高的格式来表示日期和时间。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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

续订 DHCP 租约

DHCP 还允许以手动方式或编程方式在客户端上续订租约,从而绕过客户端和服务器之间正常的重新协商过程。ipconfig.exe /renew 命令可对所有网络适配器或特定适配器执行此任务。

下面的脚本循环访问网络适配器配置集合,并使用 RenewDHCPLease 方法来续订各个配置的租约。

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 22 首先显示各个网络适配器的 DHCP 设置,然后检查各个网络适配器以查看是否启用了 DHCP。如果启用了,它便续订 DHCP 租约。

要完成此任务,脚本必须:

1.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

2.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

3.

显示标签“Settings before renewing lease”。

4.

对于集合中的每个网络适配器配置,请执行以下步骤。

5.

显示索引号、说明以及各个适配器是否启用了 DHCP。

6.

如果启用了 DHCP,则检索 DHCP 租约的获取日期和到期日期,并调用 WMIDateToString 函数将这两个日期转换成易读的格式。

显示 DHCP 服务器的 IP 地址以及租约的获取日期和到期日期。

7.

调用 Win32_NetworkAdapterConfiguration 的 RenewDHCPLease 方法,然后等待 5 秒钟让续订过程完成。

8.

如果 RenewDHCPLease 方法返回:

值 0,则显示一条消息,指出租约已续订。

值 1,则显示一条消息,指出租约已续订,并且必须重新启动计算机。

大于 1 的值,则显示一条消息,指出租约无法续订。

9.

再次查询 Win32_NetworkAdapterConfiguration 类,并再次只筛选启用了 IP 的适配器。这次重新查询是有必要的,因为每次查询都返回一个设置快照(在运行查询时找到的设置),而在设置随后发生更改时,查询并不能自动更新。

10.

重新显示早先显示的 DHCP 相关设置。

11.

WMIDateToString 函数接受 WMI DATETIME 格式的值,并将它转换成一个字符串,以便按可读性更高的格式来表示日期和时间。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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

管理静态 IP 地址

在非常小的网络上,DHCP 可能会显得大材小用,您可能只需要为客户端分配静态 IP 地址就能够管理 IP 地址分配。即使在更大、更复杂的网络上,某些主机(例如网络服务器和域控制器)也无法使用 DHCP,因而必须为它们分配静态 IP 地址。还必须将这些静态 IP 地址添加到 DHCP 服务器作用域的排除列表中。

与网络客户端配置的大多数其他方面一样,Win32_NetworkAdapterConfiguration WMI 类提供了一些方法,以便以编程方式来读取和写入这些设置。

配置静态 IP 地址

本节的脚本 Staticip-enable.vbs 使用 Win32_NetworkAdapterConfiguration 的 EnableStatic() 方法来设置网络适配器的 IP 地址和子网掩码,它们分别是以属性 IPAddress 和 IPSubnet 的形式公开的。因为这两项设置可能有不止一个值,所以这两个属性的数据类型是字符串数组。

EnableStatic() 方法还可以有效地禁用 DHCP。此脚本显示完成该任务所需要的基本代码;不过,对于分配了静态 IP 地址的客户端,还必须为其分配默认网关和 DNS 服务器,这样它才能重新建立网络连接。下一节中的脚本 Staticip-enableex.vbs 介绍如何使用脚本来执行这一系列任务。

如果已经启用了一个静态地址,则这两个脚本不会再分配新的静态 IP 地址。但是,如果在已经配置了一个静态 IP 地址的情况下,您需要分配一个新的静态 IP 地址,则可以通过删除下面几行来轻松地改编此脚本:

If objNicConfig.DHCPEnabled Then
...
Else
  WScript.Echo "    Static IP address already enabled."
End If

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 23 检查各个网络适配器以查看是否启用了 DHCP。如果启用了,则该脚本启用静态 IP 寻址,分配 IP 地址和子网掩码,并有效地禁用客户端上的 DHCP。可能还需要将配置更改传播到 DHCP 服务器,这样才能释放从 DHCP 租赁的旧 IP 地址,然后注册新的静态 IP 地址。

仅通过该脚本中介绍的方法,还不能使用静态 IP 地址重新建立网络连接。还必须设置默认网关和 DNS 服务器(如下一个脚本所示)。如果使用此脚本,您就必须手动设置它们。

要禁用 DHCP 并为客户端分配静态 IP 地址和子网掩码,该脚本必须:

1.

创建两个仅包含一个元素的数组:第一个数组包含要分配的静态 IP 地址,第二个数组包含子网掩码。

2.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

3.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

4.

循环访问集合中的各个网络适配器配置,并对每一个网络适配器执行以下步骤。

5.

显示网络适配器的索引号和说明。

6.

如果该适配器启用了 DHCP,则调用 Win32_NetworkAdapterConfiguration 的 EnableStatic 方法,并将两个已使用所需 IP 地址和子网掩码初始化了的数组变量传递给它。

7.

如果 EnableStatic 返回:

值 0(指示成功),则显示新的 IP 地址和子网掩码。

值 1,则显示一条消息指示成功,并指示必须重新启动计算机和增大重新启动计数器。

0 和 1 以外的值,则显示一条消息指示失败。

8.

如果未启用 DHCP,则显示一条消息,指示静态 IP 寻址已经启用。

9.

如果重新启动计数器大于 0,则至少对于一个网络适配器,EnableStatic 的返回值是 1。显示一条消息,指示必须重新启动计算机更改才能生效。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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.

为静态 IP 地址配置网关、DNS 和 WINS

要在启用了静态 IP 寻址并分配了 IP 地址和子网掩码后重新为客户端建立网络连接,您还必须设置新的默认网关、DNS 服务器搜索顺序和 WINS 服务器(如果网络上使用了 WINS)。然而,只有在已成功分配静态 IP 地址和子网的情况下,脚本才会执行第二组任务。因此,使用脚本执行该任务要求两级条件限制。

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 24 检查各个网络适配器以查看是否启用了 DHCP。如果启用了,则该脚本启用静态 IP 地址,分配 IP 地址和子网掩码并禁用 DHCP。如果该脚本成功完成了这些任务,它就会分配默认网关、DNS 服务器和 WINS 服务器。

1.

创建变量以指定所有必要的参数。

2.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

3.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

4.

循环访问集合中的各个网络适配器配置,并对每一个网络适配器执行以下步骤。

5.

显示网络适配器的索引号和说明。

6.

如果该适配器启用了 DHCP,则调用 Win32_NetworkAdapterConfiguration 的 EnableStatic 方法,并将两个已使用所需 IP 地址和子网掩码初始化了的数组变量传递给它。

7.

如果 EnableStatic 的返回值是 0(表示成功),则对 Win32_NetworkAdapterConfiguration 调用 Get 方法来仅返回当前实例,并使用 Index 属性进行筛选(该属性是 WMI 用来唯一标识实例的键属性)。

8.

对于网络适配器的当前实例,请调用 SetGateways、SetDNSServerSearchOrder 和 SetWINSServer 方法,并将相应的变量作为参数传递给它们。

9.

检查上述各种方法的返回值,并显示一条消息指示各种方法是成功还是失败。

10.

如果 EnableStatic 返回:

值 1,则显示一条消息指示成功,并指示必须重新启动计算机和增大重新启动计数器。

0 和 1 以外的值,则显示一条消息指示失败。

11.

如果未启用 DHCP,则显示一条消息,指示静态 IP 寻址已经启用。

12.

如果重新启动计数器返回:

大于 0 的值,那么至少对于一个网络适配器,EnableStatic 的返回值是 1。显示一条消息指示必须重新启动计算机更改才能生效,然后退出脚本。

值 0,则再次查询 Win32_NetworkAdapterConfiguration,并显示各个网络适配器的新设置以反映所做的更改。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

 

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.

方案:分配子网上的 IP 地址

此方案介绍如何管理要保留和排除的 IP 地址。在此方案中,必须对子网或其他 IP 地址范围启用 DHCP,同时为其他客户端分配同一池中的静态 IP 地址,从而确保没有将一个 IP 地址分配给了一个以上的客户端。要完成这项任务,必须对 DHCP 服务器进行相应的更改,但 DHCP 服务器管理不在本文的讨论范围之内。

要自动完成此方案中的操作,一种方法是使用以下两个脚本:

Dhcp-enable-subnet.vbs

为管理员设置的 IP 地址范围内的客户端启用 DHCP。如果客户端上已经启用了 DHCP,则此脚本将续订租约以确保客户端 DHCP 设置是正确的。

Staticip-enable-excl.vbs

中止客户端上的一系列 IP 地址的 DHCP 租约以便从 DHCP 服务器上予以排除。对这些客户端启用静态 IP 寻址,并为各个客户端分配 IP 地址、子网掩码、默认网关和 DNS 服务器。

管理员必须另外配置 DHCP 服务器的作用域,保留和排除相应的地址。但是,DHCP 服务器上的保留和排除操作不在本文的讨论范围之内。

WMI 没有 DHCP 提供程序,所以在服务器上使用脚本的可能性很有限。您可以使用命令行工具(如 Netsh.exe)在 DHCP 服务器上执行一些任务。

方案的第一部分:为整个子网配置 DHCP

要自动完成此方案中的第一组任务,第一个脚本要确保为 DHCP 服务器作用域中的正确 IP 地址范围(在脚本开头的三个变量中设置)内的客户端启用 DHCP。如果没有启用,则脚本将为这些客户端启用 DHCP。如果已经在客户端上启用了 DHCP,则脚本将续订 DHCP 租约以确保能够从服务器检索当前设置。

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 25 循环访问一组 IP 地址,并为各台计算机检查各个网络适配器是否启用了 DHCP。如果没有启用,它就会启用 DHCP。您必须指定 IP 地址的第一部分和该地址范围的开始和终止 IP 地址。

在试图对多个网络主机进行这些更改之前,此脚本执行两项错误检查(这被认为是一种很好的做法):脚本首先对主机执行 ping 命令以确保可以访问它,然后检查与 WMI 的连接是否有错误以确保主机正在运行 WMI 服务(它可能无法在较旧的操作系统上运行)。

1.

创建变量以指定用作 IP 地址前缀的参数以及用作后缀的开始值和结束值的参数(附加上这两个值才能构成完整 IP 地址)。

2.

使用 For 循环来循环执行任务,为 IP 地址范围内的各个后缀分别执行一次。

3.

针对各个后缀(实质上是针对各个 IP 地址),执行以下任务。

4.

将前缀与计数器的当前值连接起来,构成一个 IP 地址。

5.

通过使用 WshShell 对象的 Exec 方法运行 Ping.exe(使用相应参数来指定尝试次数为 2,超时设置为 1 秒)来 ping 该 IP 地址。

6.

如果主机响应了 ping,则使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

7.

检查在绑定到 WMI 时是否有错误。

8.

如果与 WMI 建立了连接,则使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

9.

对于集合中的每个网络适配器配置,请执行以下任务。

10.

显示网络适配器的索引号和说明。

11.

检查是否已经启用了 DHCP。

12.

如果 DHCP 未启用,请调用 Win32_NetworkAdapterConfiguration 的 EnableDHCP 方法。

13.

如果 EnableDHCP 方法返回:

值 0,则显示一条表示成功的消息。

任何其他值,则显示一条表示失败的消息。

14.

如果 DHCP 已经启用,则显示一条消息说明这种状况,并调用 Win32_NetworkAdapterConfiguration 的 RenewDHCPLease 方法。

15.

如果 RenewDHCPLease 方法返回:

值 0,则显示一条表示成功的消息。

任何其他值,则显示一条表示失败的消息。

16.

如果在绑定到 WMI 时出现了错误,则显示一条错误信息。

17.

如果主机没有响应 ping,则显示一条错误信息。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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.

方案的第二部分:对排除的客户端启用静态 IP 地址

要自动完成该方案中的第二组任务,第二个脚本将中止 DHCP 租约,并对从子网中排除的客户端启用静态 IP 地址。成功完成该任务后,脚本为客户端分配默认网关和 DNS 服务器,以使客户端能够重新连接到网络上。

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 26 循环访问一组主机名,并为各台计算机检查各个网络适配器是否启用了 DHCP。如果 DHCP 启用了,则脚本中止租约,然后分配静态 IP 地址和子网掩码。如果成功启用了静态 IP 寻址,请为网络适配器分配默认网关和 DNS 服务器。

1.

创建变量以指定所有必要的参数。这些参数包括要执行操作的计算机的列表,以及在启用静态 IP 寻址时为各台计算机分配的 IP 地址和其他设置。

2.

将一个循环计数器初始化为 0,该计数器用于从数组中为各台计算机选择正确的 IP 地址。

3.

循环访问要配置静态 IP 寻址的计算机列表中的各个主机名。

4.

通过使用 WshShell 对象的 Exec 方法运行 Ping.exe(使用相应参数来指定尝试次数为 2,超时设置为 1 秒)来 ping 该主机名。

5.

如果主机响应了 ping,请从数组中选择索引等于循环计数器当前值的 IP 地址。将该 IP 地址分配给仅包含一个元素的新数组;当静态 IP 寻址启用时,该数组将分配给该主机。请记住,IPAddress 属性的值是字符串数组。

6.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

7.

检查在绑定到 WMI 时是否有错误。

8.

如果与 WMI 建立了连接,则使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

9.

对于集合中的每个网络适配器配置,请执行以下任务。

10.

显示网络适配器的索引号和说明。

11.

检查是否已经启用了 DHCP。

12.

使用 GetObject 调用来连接到指定计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

13.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

14.

对于集合中的每个网络适配器配置,请执行以下任务。

15.

调用 Win32_NetworkAdapterConfiguration 的 ReleaseDHCPLease 方法来中止 DHCP 租约,并根据返回值显示成功或错误信息。

16.

调用 Win32_NetworkAdapterConfiguration 的 EnableStatic 方法,并将该主机的仅包含一个元素的 IP 地址数组和仅包含一个元素的子网掩码数组(后者对所有主机都一样)传递给该方法。

17.

如果 EnableStatic 方法成功,请调用 Get 方法以获取对 Win32_NetworkAdapterConfiguration 的当前实例的一个新引用。这将刷新该对象的属性以便进行进一步的更改。

18.

调用 Win32_NetworkAdapterConfiguration 的 SetGateways 和 SetDNSServerSearchOrder 方法,将相应的变量作为参数传递给它们。

19.

检查这两种方法的返回值,并分别为它们显示指示成功或失败的消息。

20.

如果无法分配静态 IP 地址,则显示一条错误信息。

21.

如果未启用 DHCP,则显示一条消息,指示静态 IP 寻址已经启用。

22.

再次查询启用了 IP 的适配器的 Win32_NetworkAdapterConfiguration 类以检索反映刚进行的更改的任何新值,并显示相关属性。

23.

如果在绑定到 WMI 时出现了错误,则显示一条错误信息。

24.

如果主机没有响应 ping,则显示一条错误信息。

25.

增大用来从数组中选择 IP 地址的循环计数器。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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.

方案:在静态 IP 地址和 DHCP 之间切换

在此方案中,一位“经常出差的员工”需要在不同的分公司,将其膝上型计算机连接到公司网络。在某些情况下,网络要求客户端使用 DHCP;在另外一些情况下,计算机必须使用静态地址(配合使用子网掩码、默认网关、DNS 服务器和 WINS 服务器)。要运行此脚本,用户需要键入脚本的名称,随后键入一个空格和计算机当前所在的办公室的名称。对于不同的位置,此脚本选用不同的地址分配方法:在 Miami 和 Dogpatch 选用静态;而在 Seattle 和 Boston 选用 DHCP。

脚本步骤

caution.gif  警告
这个脚本可能会更改您的计算机配置。只能在测试计算机上运行此脚本,并在运行前记下涉及的设置。

列表 27 通过使用由用户输入的代表当前位置的命令行参数,使用户能够在便携式计算机上在 DHCP 和静态 IP 寻址之间切换。该脚本分为几个子例程,使其更加模块化,更便于阅读、调试和修改。

此脚本使用 WScript.Arguments 属性,它是 Windows Script Host 的一部分。该脚本返回在命令行中脚本名称后键入的所有参数的集合。有关使用该属性的详细信息,请参见 Windows 2000 Scripting Guide(Windows 2000 脚本指南)的“WSH Primer”(WSH 入门)一节中的“Working with Command-Line Arguments”(使用命令行参数),网址为 http://go.microsoft.com/fwlink/?LinkId=29994。

1.

使用 WScript.Arguments 集合检索在脚本名称后输入的命令行参数。

该脚本只使用一个参数:用户要连接到局域网的办公室的名称。将忽略任何其他参数。

2.

将第一个参数 colArgs(0) 分配给变量 strOffice。

3.

使用 Select Case 语句,将布尔值 True 或 False 分配给 blnDHCP,具体取决于作为命令行参数输入的分公司名称。

如果此参数不是四个有效名称中的任何一个,脚本将显示一条错误信息并退出。

4.

使用 GetObject 调用来连接到本地计算机上的 WMI 名称空间 root\cimv2,并将模拟级别设置为“impersonate”。

5.

使用 ExecQuery 方法查询 Win32_NetworkAdapterConfiguration 类,并使用“WHERE IPEnabled = True”来筛选 WQL 查询。

这将返回一个集合,它由启用了 IP 的计算机上的所有网络适配器配置组成。

6.

如果将其名称作为参数传递的办公室使用 DHCP,则调用 SetDHCP 子例程。

7.

如果该办公室不使用 DHCP,则调用 SetStaticIP 子例程。

8.

SetDHCP 子例程检查 DHCPEnabled 属性;如果 DHCP 未启用,则调用 EnableDHCP 方法。如果 DHCP 已经启用,则 SetDHCP 会显示一条消息说明这种状况,并显示 DHCP 服务器的 IP 地址。

在结束之前,SetDHCP 调用 GetSettings 子例程。

如果 DHCP 已经启用,您可能需要向续订租约的子例程添加代码。上一个方案中的 Dhcp-enable-subnet.vbs 提供了一个有关如何执行此操作的示例。虽然 DHCP 客户端应该查找本地 DHCP 服务器并获得本地设置,但是在某些网络环境中,续订租约可以加速该过程。

9.

SetStaticIP 子例程是以一些硬编码变量开头的,这些变量分配静态 IP 寻址所必需的设置(更复杂的脚本可以从外部源获得这些设置)。然后,SetStaticIP 子例程检查 DHCPEnabled 属性;如果 DHCP 已经启用,该子例程调用 EnableStatic 方法。如果 EnableStatic 成功,SetStaticIP 就调用 SetGateways 和 SetDNSServerSearchOrder 方法来完成静态 IP 配置。

如果 DHCP 已经启用,则 SetDHCP 会显示一条消息说明这种状况,并显示 DHCP 服务器的 IP 地址。

在结束之前,SetStaticIP 调用 GetSettings 子例程。

10.

GetSettings 子例程由 SetDHCP 和 SetStaticIP 调用,它再次查询 Win32_NetworkAdapterConfiguration 以检索由先前的子例程所做的任何更改。然后,GetSettings 会显示计算机上当前的相关 IP 地址分配设置。

列表 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

当您使用 Cscript.exe 来运行这个脚本时,命令窗口中会显示与以下内容类似的输出:

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

用于管理客户端上的 IP 地址分配的工具

表 11 列出了一些可用于通过脚本管理客户端上的 IP 地址分配的 Windows 工具。

表 11   用于管理客户端上的 IP 地址分配的工具

技术工具获取来源

命令行工具

Dhcploc.exe:DHCP 服务器定位器实用工具

Windows Server 2003 支持工具

命令行工具

Enabledhcp.vbs

Windows 2000 Resource Kit

命令行工具

Netsh.exe

Windows 操作系统1

WSH

 

WMI

Win32_NetworkAdapterConfiguration

 

1Windows 2000、Windows XP 和 Windows Server 2003。其他版本的 Windows 上也可能有此工具。

表 12 列出了一些可用于通过脚本管理客户端上的 IP 地址的注册表项。

caution.gif  警告
注册表编辑不当可能会严重破坏您的系统。在更改注册表之前,应该先备份计算机上所有有用的数据。

表 12   与使用脚本管理客户端上的 IP 地址分配相关的注册表子项

注册表子项

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


返回页首返回页首上一页第 5 页,共 11 页下一页
**
**