Transcript WMI scripts
WMI
廖凡磊
1
agenda
► Namespace
► WMI
scripts
► WMIC
► WMI security
2
Namespace
\ROOT
CIMV2
Default
WMI
security
3
Namespace (cont.)
classes are organized into namespaces.
► control the scope and visibility of managed
resource class definitions.
► contains a logical group of related classes
representing a specific technology or area of
management.
► Namespaces are equivalent to folders
► CIM
4
Namespace(cont.)
► Default
namespace
root/CIMV2
►絕大多數與計算機、操作系統相關聯的命名空間
root/Default
►管理註冊表的命名空間
root/Security
root/WMI
5
Class category
► Core
and Common Classes
► Extension Classes
6
Core and Common Classes
► Define
in root\cimv2
► classes prefaced with “CIM_”
► 271 / 275 is abstract classes –
► 4 / 275 is dynamic classes
Win32 Provider (cimwin32.dll)
CIM_DataFile
CIM_DirectoryContainsFile
CIM_ProcessExecutable
CIM_VideoControllerResolution
7
Extension Classes
► Define
in the root\cimv2
► identified by the “Win32_” prefix
► 68/463 are abstract classes
► 395/463 are dynamic classes
► you can directly use them in your WMI
scripts.
8
Property and value
class
property
computer
\\DARYL\root\CIMV2:Win32_NTLogEvent.Logfile=“Application”.
RecordNumber=“1”
value
namespce
9
Listing Classes in a Namespace
► Example
of WMI script
► Find specific class which contains string
cscript GetClasses.vbs |findstr /I "win32_tssessionsetting"
cscript GetClasses.vbs |findstr /I “__"
cscript GetClasses.vbs |findstr /I “CIM_"
cscript GetClasses.vbs |findstr /I "win32_"
10
Exploring the CIM Repository
► WMI
Tester
Wbemtest .exe
► CIM
Studio
part of the WMI SDK
Web-based interface
► WMI
scripts
11
Exploring the CIM Repository (cont.)
Wbemtest
► run
-> wbemtest
► 連線-> root/cimv2
12
Exploring the CIM Repository (cont.)
CIM Studio
► Download
WMI tools
► http://www.microsoft.com/downloads/detail
s.aspx?familyid=6430F853-1120-48DB8CC5-F2ABDC3ED314&displaylang=en
13
Exploring the CIM Repository (cont.)
WMI
script
strComputer = "."
Set objSWbemServices = GetObject("winmgmts:\\" & strComputer & "\root")
Set colNameSpaces = objSwbemServices.InstancesOf("__NAMESPACE")
For Each objNameSpace In colNameSpaces
Wscript.Echo objNameSpace.Name
Next
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
SECURITY
RSOP
Cli
SecurityCenter
WMI
CIMV2
Policy
Microsoft
DEFAULT
directory
14
Creating a WMI Script
► Environment:
OS support WMI
► Scripting language that supports Microsoft
ActiveX script hosting
Visual Basic Scripting Edition
Microsoft JScript
Perl
Windows Script Host
Active Server Pages
Internet Explorer
15
The flow of creating WMI scripts
Connect to default CIM namespace 1. To connect to WMI using SWbemLocator
Connect to specific CIM namespace 2. To connect to WMI and retrieve an object
using a moniker prefix
Get instance of class
1. Get instance collection using InstancesOf
method
2. Get instance collection using ExecQuery
method
3. Get specific instance using Get method
4. Get specific instance using moniker prefix
1. Wscript.echo
Print
16
Background
►
命名規則
col
obj
►
syntax
►
a collection reference
a object reference
‘
comment
&
connect two string
_
uncompletely keyword, put _ at end of line
No need ;
WQL
WMI Query Language
a subset of the American National Standards Institute Structured
Query Language (ANSI SQL)
tutorial
17
connect to Default CIM namespace
► The
default namespace is defined by the
following registry entry:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Scripting\Default
Namespace
default namespace:root/cimv2
► Using SWbemLocator in default namespace
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objService = objLocator.ConnectServer
► Using
moniker in default namespace
strComputer = "."
Set objService = GetObject("winmgmts:“)
18
Connect to specific CIM
Namespace
► Using
SWbemLocator
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objService = objLocator.ConnectServer(".", "root\cimv2")
► Using
moniker
winmgmts:[{SecuritySettings}!][\\ComputerNa
me][\Namespace][:ClassName][.Key]
strComputer = "."
Set objService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
19
Get instance of class
► InstancesOf
Set objSWbemObjectSet = objSWbemServices.InstancesOf("Win32_Processor
")
► ExecQuery
Set objSWbemObjectSet = objSWbemServices.ExecQuery("select ProcessorId
from Win32_Processor where DeviceID='cpu0'")
► Get
SwbemServices.Get([strObjectPath][.KeyProp
erty='Value'])
Set objSWbemObject =
objSWbemServices.Get("Win32_Processor.DeviceID='cpu0'")
20
Get instance of class (cont.)
► moniker:
winmgmts:[{SecuritySettings}!][\\ComputerNa
me][\Namespace][:ClassName][.Key]
Set objSWbemObject =
GetObject("winmgmts:Win32_Processor.DeviceID='cpu0'")
21
Print
1.Object
Wscript.echo “CPU的型號為:" & objSWbemObject.name
2.collection
For Each objSWbemObject In objSWbemObjectSet
Wscript.echo “CPU的型號為:" & objSWbemObject.name
Next
22
Example1
strComputer = "."
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer //預設root/CIMV2
Set objSWbemObjectSet = objSWbemServices.InstancesOf("Win32_Processor")
For Each objSWbemObject In objSWbemObjectSet
Wscript.echo “CPU的型號為:" & objSWbemObject.name
Next
strComputer = ".“
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer //預設root/CIMV2
Set objSWbemObjectSet = objSWbemServices.ExecQuery("SELECT * From
Win32_Processor")
For Each objSWbemObject In objSWbemObjectSet
Wscript.echo "CPU的型號為:" & objSWbemObject.name
Next
23
This script enumerates all of the cpu on the local computer system.
Example2
strComputer = "."
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objServices = objLocator.ConnectServer(".", "root\cimv2")
Set objObjectSet = objServices.InstancesOf("Win32_NetworkAdapter")
For Each objObject In objObjectSet
Wscript.echo objObject.Caption & " " &objObject.MacAddress
Next
strComputer = "."
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objServices = objLocator.ConnectServer(".", "root\cimv2")
Set objObjectSet = objServices.ExecQuery("SELECT MACAddress,Caption
FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND
(Manufacturer <> 'Microsoft'))")
For Each objObject In objObjectSet
Wscript.echo objObject.Caption & " " &objObject.MacAddress
Next
24
比較各種 WMI 例項擷取方法與查詢
25
Ref:https://www.microsoft.com/taiwan/msdn/library/2003/Feb-2003/scripting01142003.htm
Monitoring Resources by Using WMI
Event Notifications
► How
can we know system state
Write a WMI script and run it repeatly
Interval problem
drawback
►Not
► What
real time
you can do in WMI Event Notification
Free disk space notification
Process notification
26
Example
1.A connection is made to a
WMI namespace on a computer.
strComputer = "."
Set objSWbemServices = GetObject("winmgmts:" &_
2.A notification
"{impersonationLevel=impersonate}!" &_
query is issued.
"\\" & strComputer & "\root\cimv2")
Set objEventSource = objSWbemServices.ExecNotificationQuery( _
"SELECT * FROM __InstanceCreationEvent " &_
"WITHIN 10 " &_ "WHERE TargetInstance " &_
"ISA 'Win32_Process' " &_
"AND TargetInstance.Name = 'notepad.exe'")
3.The event is
received and some
action performed.
Set objEventObject = objEventSource.NextEvent()
Wscript.Echo "An instance of notepad.exe just started."
27
Example
strComputer = "."
Set objSWbemServices = GetObject("winmgmts:" &_
"{impersonationLevel=impersonate}!" &_
"\\" & strComputer & "\root\cimv2")
Set objEventSource = objSWbemServices.ExecNotificationQuery( _
"SELECT * FROM __InstanceModificationEvent " &_
"WITHIN 10 " &_ "WHERE TargetInstance " &_
"ISA 'Win32_Service' " &_
"AND TargetInstance.Name = 'alerter '")
Set objEventObject = objEventSource.NextEvent()
Wscript.Echo "The status of the alerter service just changed ."
28
使用 WMI 問題排除
// 使用 WMI 來抓取某台電腦的磁碟資訊.
strComputer = "172.16.9.228"
Set objWMIService = GetObject("winmgmts:" _
&"{impersonationLevel=Impersonate," _
& "authenticationLevel=Pkt}!" _
& strComputer & " root/cimv2")
Set colDisks = objWMIService.ExecQuery _
("Select * from Win32_LogicalDisk")
For each objDisk in colDisks Wscript.Echo "DeviceID: " & vbTab & _
objDisk.DeviceID & vbNewLine & _
"FreeSpace: " & vbTab & objDisk.FreeSpace
Next
Ref:http://www.wretch.cc/blog/redray/1821552
29
problem on remote WMI script
► C:MyWorkSpacemyVbs
est2.vbs(15, 1)
SWbemLocator: 存取被拒。
► 這主要是由於 Windows XP 本身作業系統是使用 網
路存取:本機帳戶的共用和安全性模式 -> 預設 (僅
限來賓:本機使用者以來賓身份驗證。)
► 所有的帳戶都是當成來賓來認證, 也就無法使用
WMI這項服務, 我們必須將此選項修改成
► 網路存取:本機帳戶的共用和安全性模式 -> 傳統:
本機使用者以自已的身份驗證。
► 這樣才能使用所指定的帳號密碼來存取 WMI 服務.
Ref:http://www.wretch.cc/blog/redray/1821552
30
problem on remote WMI script (cont.)
C:wmi_info.vbs(47, 2) SWbemLocator: 無法取得 RPC 伺服
器。
► 這個問題大多出現在我們無法連線到欲取得資訊的電腦時,
最可能的原因是防火牆的問題
► 如果是微軟的防火牆 參照MSDN
► 如果是別的防火牆打開 TCP 連接埠 :
►
135
445
1024 ~ 1034 (一般情況)
►
如果還是不行, 請確定電腦上的 WMI 服務有開啟, 請將 [系
統管理工具] -> [服務] 中的 Windows Management
Instrumentation 開啟.
31
WMIC
► Windows
Management Instrumentation
Command-line
► c:\windows\
► 執行模式
交互模式
►wmic:root\cli>os
/?
非交互模式
►wmic
os /?
32
commands
► CALL
Executes a method.
wmic:root\cli>SERVICE WHERE CAPTION='TELNET' CALL STARTSERVICE
► CREATE
Creates a new instance and sets the property
values. CREATE cannot be used to create a new
class.
wmic:root\cli>ENVIRONMENT CREATE NAME="TEMP",
VARIABLEVALUE="NEW"
► DELETE
Deletes the current instance or set of instances.
DELETE can be used to delete a class.
wmic:root\cli>PROCESS WHERE NAME="CALC.EXE" DELETE
33
Commands (cont.)
► GET
Retrieve specific property values.
wmic:root\cli>PROCESS GET NAME
► LIST
Shows data. LIST is the default verb.
Adverb
Description
BRIEF
Core set of the properties.
FULL
Full set of properties. This is the default adverb for LIST.
INSTANCE
Instance paths only.
STATUS
Status of the objects.
SYSTEM
System properties.
wmic:root\cli>PROCESS LIST BRIEF
34
Commands (cont.)
► CONTEXT
view the current value of the conditions set
wmic:root\cli>context
35
簡單管理工作範例
wmic:root\cli> bios list full
wmic:root\cli>process list brief
36
複雜管理工作範例
► 查詢事件日誌並產生結果文件
C:\>WMIC /node:"dc2" /user:"mytest" NTEVENTswheres"eventtype<3 and
eventtype>0 AND logfile='Application'" GET Logfile, SourceName, Eventtype,
Message, TimeGenerated
/FORMAT:htable:"sortby=EventType">c:\Application.htm
► 使用WMIC同時重新啟動多台被管理的伺服器
或工作站
C:\>WMIC /NODE:@"c:\MyServerList.txt" OSswheres(Primary="TRUE") CALL
Win32ShutDown 6
37
WMI Security
► WMI
is powerful
► Easy to run a script
► WMI scripts run in the security context of
the user running the script
► WMI namespace-level security.
► DCOM security
► Standard Windows Operating System
Security
38
WMI namespace-level security
39
Ref:http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_ocmw.mspx
WMI namespace-level security
► Setting
Namespace Security Descriptors
WMI control properties
40
Distributed COM (DCOM) security
►
Impersonation enables you to specify whom the WMI
service should act as when carrying out a task
It is possible to allow Computer B to also use your credentials; for
that matter, you can also allow computers C, D, and E to use your
credentials.
No double delegation
►
►
The authenticationLevel setting enables you to request the
level of DCOM authentication and privacy to be used
throughout a connection.
Setting the Default Process Security Level Using VBScript
use a moniker in a call to GetObject
41
Distributed COM (DCOM) security
DEMO
A
B
O
A
C
O
A
B
C
X
42
Standard Windows Operating System
Security
► Copy
files from a NTFS permissions folders
will cause “ACCESS DENIED”
43
review
► Namespace
► WMI
scripts
► WMIC
► WMI security
44
Reference
►
►
►
►
►
►
►
►
►
►
►
►
►
►
►
►
►
►
►
►
►
完整的線上手冊在這:
http://msdn2.microsoft.com/en-us/library/aa394582.aspx
MSDN Library for Visual Studio 2005 也內含。
另外到下載中心搜尋 WMI ,勾選英文,會有一些工具及範例可以抓來測:
http://www.microsoft.com/downloads/results.aspx?DisplayLang=zhtw&nr=20&freetext=WMI&DisplayEnglishAlso=true&sortCriteria=date
中文資訊主要都是 TechNet 那邊翻譯 Script Center 的:
http://www.microsoft.com/taiwan/technet/scriptcenter/default.mspx
這邊也有工具及範例的連結。
Happy scripting
http://www.microsoft.com/taiwan/technet/columns/profwin/tnascript.mspx
WMI - Windows Management Instrumentation 。提供資源讓您透過指令碼管理 Windows
作業系統的一種技術。請參閱 WMI Scripting
WMI輕鬆入門(簡)
http://hi.baidu.com/xuejinglan/blog/item/1f9d632cbffbcaee8a139912.html
WMIC 全新的超級指令行系統管理工具
http://forum.slime.com.tw/thread61654.htm
WMI使用技巧
http://ptt.hit.edu.cn/api/blog.aspx?title=wmi%E4%BD%BF%E7%94%A8%E6%8A%80%E5%B7
%A7l
WMI tools
http://www.microsoft.com/downloads/details.aspx?familyid=6430F853-1120-48DB-8CC5F2ABDC3ED314&displaylang=en
Namespaces
http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_khjg.mspx?mfr=true
45
strComputer = "."
Set objServices = GetObject("winmgmts:\\" _
& strComputer & "\root\CIMV2")
set objProcessSet = objServices.ExecQuery _
("SELECT Name FROM Win32_Process",,48)
For Each Process in objProcessSet
WScript.Echo Process.Name
Next
strComputer = "."
Set objServices = GetObject( _
"winmgmts:{impersonationLevel=impersonate," _
& "authenticationLevel=pktPrivacy}!root/cimv2")
set objProcessSet = objServices.ExecQuery _
("SELECT Name FROM Win32_Process",,48)
For Each Process in objProcessSet
WScript.Echo Process.Name
Next
46
► Impersonation
level, expressed as
"winmgmts:{impersonationLevel=Value}".
► Authentication level, expressed as
"winmgmts:{authenticationLevel=Value}".
47
DCOM Impersonation Levels
Anonymous
Hides the credentials of
the caller.
identity
Enables objects to query
the credentials of the
caller.
Enables objects to use the
credentials of the caller.
impersonate
delegate
Enables objects to permit
other objects to use the
credentials of the caller.
48
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Scripting\Default Impersonation Level
Authentication Level
NONE
CONNECT
CALL
PKT
PKTINTEGRITY
PKTPRIVACY
DEFAULT
back
Does not use any
authentication.
only when the client tries
to connect to the server
only at the beginning of
each call
Signed theHeader
Signed the all packet
Signed and encrypts all
packet
Uses a standard security
49
How to use WMI control properties
► 我的電腦
右鍵->管理->服務及應用程式>WMI控制 右鍵->內容
► Log
► Backup/restore
► Security on namespace
► Default namespace specified
50
back