WMI 應用——用 VBScript 編寫類似 ipconfig 的工具_終南的IT空間

chief1985發表於2008-10-12
導讀:


WMI 應用——用 VBScript 編寫類似 ipconfig 的工具


作者:終南   <li.zhongnan@hotmail.com>



在Windows下,WSH的功能是非常強大的。WMI 則提供了非常豐富的介面,可以與系統進行互動,獲取系統相關資訊,並能對系統中的裝置和物件進行有效管理。


Windows中的ipconfig 工具提供了與系統網路裝置的介面,WMI 中同樣有相同的介面,因此可以利用 VBScript 編寫指令碼來實現類似 ipconfig 的功能。利用 WMI 介面可以實現的網路管理功能非常之多,此處僅以顯示IP地址、釋放和獲取DHCP地址為例做一說明:


1、顯示IP地址


通過 Win32_NetworkAdapterConfiguration 獲取網路配置資訊,判斷網路介面卡是否支援IP協議。然後利用Win32_NetworkAdapter 物件或取網路卡資訊,Win32_NetworkAdapter有很多屬性,重要的包括NetConnectionStatus、NetConnectionID、MACAddress、IPAddress等。所有ipconfig顯示出的資訊都能夠獲取得到,那麼需要做的工作就是按照 ipconfig 顯示格式來排列一下這些資訊,使其看起來好看些。


2、釋放和獲取DHCP地址


呼叫Win32_NetworkAdapterConfiguration物件的ReleaseDHCPLease()和RenewDHCPLease()方法來實現。


3、新增上幫助說明、整理一下指令碼的結構,於是就有了:


'******************************************************************************
' 程式名: ipconfig.vbs
' 功能: 類似ipconfig的 WSH 指令碼程式, 提供了 ipconfig 的一部分功能,可以用來顯示
'       IP地址資訊, 釋放和獲取DHCP地址
' 作者:
li.zhongnan@hotmail.com (http://hi.baidu.com/li_zhongnan)
' 參考:
http://www.reskit.net/monad/net1.htm
'******************************************************************************


On Error Resume Next


isShowHelp = False
isShowIpConfig = True
isRelease = False
isRenew = False


isShowAll = False


'處理命令列引數,如果帶引數 /all 則顯示較為詳細的資訊
Set objArgs = WScript.Arguments
If objArgs.Count > 0 Then
If objArgs(0) = "/all" Then
    isShowAll = True
End If
If objArgs(0) = "/?" Then
    isShowHelp = True
    isShowIpConfig = False
End If
If objArgs(0) = "/release" Then
    isRelease = True
    isShowIpConfig = False
End If
If objArgs(0) = "/renew" Then
    isRenew = True
    isShowIpConfig = False
End If
End If


If isShowHelp Then
ShowHelp()
End If
If isShowIpConfig Then
ShowIpConfig(isShowAll)
End If
If isRelease Then
ReleaseDHCP()
ShowIpConfig(False)
End If
If isRenew Then
RenewDHCP()
ShowIpConfig(False)
End If



'******************************************************************************
' 函式: ShowHelp
' 顯示幫助資訊
'******************************************************************************
Function ShowHelp
WScript.Echo
WScript.Echo "USAGE:"
WScript.Echo "    ipconfig [/? /all /release]"
WScript.Echo "where"
WScript.Echo "    Options:"
WScript.Echo "       /?         Display this help message"
WScript.Echo "       /all       Display full configuration information"
WScript.Echo "       /release   Release the IP address for the specified adapter"
WScript.Echo "       /renew     Renew the IP address for the specified adapter"
WScript.Echo
WScript.Echo "The default is to display only the IP address, subnet mask and"
WScript.Echo "default gateway for each adapter bound to TCP/IP"
End Function


'******************************************************************************
' 函式: ShowHelp
' 顯示幫助資訊
'******************************************************************************
Function ShowHelp
WScript.Echo
WScript.Echo "USAGE:"
WScript.Echo "    ipconfig [/? /all /release]"
WScript.Echo
WScript.Echo "where"
WScript.Echo
WScript.Echo "    Options:"
WScript.Echo "       /?           Display this help message"
WScript.Echo "       /all         Display full configuration information"
WScript.Echo "       /release     Release the IP address for the specified adapter"
WScript.Echo
WScript.Echo "The default is to display only the IP address, subnet mask and"
WScript.Echo "default gateway for each adapter bound to TCP/IP."
End Function


'******************************************************************************
' 函式: ShowIpConfig(showAll)
' 顯示網路配置資訊
'******************************************************************************
Function ShowIpConfig(showAll)
'準備獲取全域性資訊
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
strKeyPath1 = "SYSTEM/CurrentControlSet/Services/Tcpip/Parameters"
strKeyPath2 = "SYSTEM/CurrentControlSet/Services/NetBT/Parameters"
strHostEntry = "Hostname"
strDomainEntry = "Domain"
strNodeEntry = "DhcpNodeType"
strRoutingEntry = "IPEnableRouter"

'通過登錄檔獲取主機名稱、域名、節點型別、是否支援IP路由、是否支援WINS代理、DNS搜尋字首等資訊
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!//" & _
   strComputer & "/root/default:StdRegProv")
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath1,strHostEntry,strHostname
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath1,strDomainEntry,strDomain
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath2,strNodeEntry,dwNodeType
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath1,strRoutingEntry,dwIPRouting
  
Select Case dwNodeType
    Case 4 strNodeType = "Mixed"
    Case 8 strNodeType = "Hybrid"
    Case Else strNodeType = "Unknown"
End Select
If dwIPRouting = 0 Then
    strIPRouting = "No"
ElseIf dwIPRouting = 1 Then
    strIPRouting = "Yes"
Else
    strIPRouting = "?"
End If
  

'通過WMI Win32_NetworkAdapterConfiguration物件獲取支援IP功能的網路介面卡配置資訊
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
   & "{impersonationLevel=impersonate}!//" & strComputer & "/root/cimv2")
  
Set colFirstNicConfig = objWMIService.ExecQuery _
   ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objFirstNicConfig In colFirstNicConfig
    strDnsWins = objFirstNicConfig.DNSEnabledForWINSResolution
Next
If strDnsWins = False Then
    strWinsProxy = "No"
ElseIf strDnsWins = True Then
    strWinsProxy = "Yes"
Else
    strWinsProxy = "?"
End If
  
'顯示全域性資訊
WScript.Echo VbCrLf & "Windows IP Configuration" & VbCrLf
If showAll Then
    WScript.Echo "        Host Name . . . . . . . . . . . . : " & strHostname
    WScript.Echo "        Primary DNS Suffix . . . . . . . : " & strDomain
    WScript.Echo "        Node Type . . . . . . . . . . . . : " & strNodeType
    WScript.Echo "        IP Routing Enabled. . . . . . . . : " & strIPRouting
    WScript.Echo "        WINS Proxy Enabled. . . . . . . . : " & strWinsProxy
    WScript.Echo "        DNS Suffix Search List. . . . . . : " & strDomain
End If
  
Set colNicConfigs = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
sngOsVer = GetOsVer
  
'先是每個網路卡的網路配置資訊
For Each objNicConfig In colNicConfigs
    intIndex = objNicConfig.Index
    Set objNic = objWMIService.Get("Win32_NetworkAdapter.DeviceID=" & intIndex)
  
    strAdapterType = objNic.AdapterType
    If IsEmpty(strAdapterType) Or IsNull(strAdapterType) Or _
     (strAdapterType = "") Then
      strAdapterType = "Network"
    End If
  
    If sngOsVer > 5 Then
      strNetConn = objNic.NetConnectionID
    Else
      strNetConn = intIndex
    End If
  
    WScript.Echo VbCrLf & strAdapterType & " adapter " & strNetConn
    WScript.Echo
    If objNic.NetConnectionStatus <> 2 Then 'not connected   
      Select Case objNic.NetConnectionStatus
        Case 0 strConnStatus = "Disconnected"
        Case 1 strConnStatus = "Connecting"
        Case 3 strConnStatus = "Disconnecting"
        Case 4 strConnStatus = "Hardware not present"
        Case 5 strConnStatus = "Hardware disabled"
        Case 6 strConnStatus = "Hardware malfunction"
        Case 7 strConnStatus = "Media disconnected"
        Case 8 strConnStatus = "Authenticating"
        Case 9 strConnStatus = "Authentication succeeded"
        Case 10 strConnStatus = "Authentication failed"
        Case 11 strConnStatus = "Invalid address"
        Case 12 strConnStatus = "Connecting"
        Case Else strConnStatus = "Credentials required"
      End Select
      ' 如果 NetConnectionStatus 的值為 7, 說明網線被拔掉了, 因此通過迴圈檢測 Win32_NetworkAdapter 物件的 NetConnectionStatus 屬性, 就可以判斷網線是否被拔掉
      WScript.Echo "        Connection Status . . . . . . . . : " & _
       strConnStatus
      If showAllInfo Then
        WScript.Echo "        Description . . . . . . . . . . . : " & _
         objNicConfig.Description
        WScript.Echo "        Physical Address. . . . . . . . . : " & _
         objNicConfig.MACAddress
      End If
    Else   
      WScript.Echo "        Connection-specific DNS Suffix . : " & _
       objNicConfig.DNSDomain
      If showAll Then
        WScript.Echo "        Description . . . . . . . . . . . : " & _
         objNicConfig.Description
        WScript.Echo "        Physical Address. . . . . . . . . : " & _
         objNicConfig.MACAddress
        WScript.Echo "        DHCP Enabled. . . . . . . . . . . : " & _
         objNicConfig.DHCPEnabled
      End If
    
      strIPAddresses = ""
      If Not IsNull(objNicConfig.IPAddress) Then
        For Each strIPAddress In objNicConfig.IPAddress
          strIPAddresses = strIPAddresses & strIPAddress & " "
        Next
      End If
      WScript.Echo "        IP Address. . . . . . . . . . . . : " & strIPAddresses
      strIPSubnets = ""
      If Not IsNull(objNicConfig.IPSubnet) Then
        For Each strIPSubnet In objNicConfig.IPSubnet
          strIPSubnets = strIPSubnets & strIPSubnet & " "
        Next
      End If
      WScript.Echo "        Subnet Mask . . . . . . . . . . . : " & strIPSubnets
      strDefaultIPGateways = ""
      If Not IsNull(objNicConfig.DefaultIPGateway) Then
        For Each strDefaultIPGateway In objNicConfig.DefaultIPGateway
          strDefaultIPGateways = strDefaultIPGateways & strDefaultIPGateway & " "
        Next
      End If
      WScript.Echo "        Default Gateway . . . . . . . . . : " & _
       strDefaultIPGateways
      If showAll Then
        WScript.Echo "        DHCP Server . . . . . . . . . . . : " & _
         objNicConfig.DHCPServer
        strDNSServerSearchOrder = ""
        If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
          For Each strDNSServer In objNicConfig.DNSServerSearchOrder
            strDNSServerSearchOrder = strDNSServerSearchOrder & VbCrLf & _
            "                                            " & strDNSServer
          Next
        End If
        WScript.Echo "        DNS Servers . . . . . . . . . . . :" & _
         strDNSServerSearchOrder
        If Not IsNull(objNicConfig.WINSPrimaryServer) Then
          WScript.Echo "        Primary WINS Server . . . . . . . : " & _
           objNicConfig.WINSPrimaryServer
        End If
        If Not IsNull(objNicConfig.WINSSecondaryServer) Then
          WScript.Echo "        Secondary WINS Server . . . . . . : " & _
           objNicConfig.WINSSecondaryServer
        End If
        If objNicConfig.DHCPEnabled Then
          dtmRawLeaseObtainedDate = objNicConfig.DHCPLeaseObtained
          strFormattedLeaseObtainedDate = WMIDateToString(dtmRawLeaseObtainedDate)
          WScript.Echo "        Lease Obtained. . . . . . . . . . : " & _
           strFormattedLeaseObtainedDate
          dtmRawLeaseExpiresDate = objNicConfig.DHCPLeaseExpires
          strFormattedLeaseExpiresDate = WMIDateToString(dtmRawLeaseExpiresDate)
          WScript.Echo "        Lease Expires . . . . . . . . . . : " & _
          strFormattedLeaseExpiresDate
        End If
      End If
    End If
Next
End Function



'******************************************************************************
' 函式: RenewDHCP
' 獲取DHCP地址
'******************************************************************************
Function RenewDHCP
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
    objNicConfig.RenewDHCPLease()
Next
End Function


'******************************************************************************
' 函式: ReleaseDHCP
' 釋放DHCP地址
'******************************************************************************
Function ReleaseDHCP
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
    objNicConfig.ReleaseDHCPLease()
Next
End Function

'******************************************************************************
' 函式: WMIDateStringToDate(dtmDate)
' 將 WMI 日期轉換成字串
'******************************************************************************
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

'******************************************************************************
' 函式: GetOsVer
' 獲取作業系統版本號
'******************************************************************************
Function GetOsVer
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
   & "{impersonationLevel=impersonate}!//" & strComputer & "/root/cimv2")
Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
For Each objOperatingSystem In colOperatingSystems
    GetOSVer = CSng(Left(objOperatingSystem.Version, 3))
Next
End Function


本文轉自
http://hi.baidu.com/li_zhongnan/blog/item/8a3f8dad1696280f4a36d628.html

相關文章