WMI 應用——用 VBScript 編寫類似 ipconfig 的工具
作者:終南 <[email protected]>
在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地址
' 作者: [email protected] (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