监视事件Monitoring Events

系统管理员可以使用 WMI 来监视网络上的事件。System administrators can use WMI to monitor events on a network. 例如:For example:

  • 服务意外停止。A service stops unexpectedly.
  • 服务器不可用。A server becomes unavailable.
  • 磁盘驱动器的容量为80%。A disk drive fills to 80% capacity.
  • 向 NT 事件日志报告安全事件。Security events are reported to an NT Event Log.

WMI 支持事件检测和传递到事件使用者,因为某些 WMI 提供程序是事件提供程序。WMI supports event detection and delivery to event consumers because some WMI providers are event providers. 有关详细信息,请参阅 接收 WMI 事件For more information, see Receiving a WMI Event.

事件使用者 是请求事件通知,然后在发生特定事件时执行任务的应用程序或脚本。Event consumers are applications or scripts that request notification of events, and then perform tasks when specific events occur. 你可以创建事件监视脚本或在事件发生时临时监视的应用程序。You can create event monitoring scripts or applications that temporarily monitor when events occur. WMI 还提供了一组预安装的永久事件提供程序和使你能够永久监视事件的永久使用者类。WMI also supplies a set of preinstalled permanent event providers and the permanent consumer classes that enable you to permanently monitor events. 有关详细信息,请参阅 使用标准使用者监视和响应事件For more information, see Monitoring and Responding to Events with Standard Consumers.

本主题中讨论了以下部分:The following sections are discussed in this topic:

使用临时事件使用者Using Temporary Event Consumers

临时事件使用者是返回与事件查询或筛选器匹配的事件的脚本或应用程序。Temporary event consumers are scripts or applications that return the events that match an event query or filter. 临时事件查询通常使用 c + + 应用程序中的 IWbemServices:: ExecNotificationQuery 或在脚本和 Visual Basic 中 SWbemServices.ExecNotificationQueryTemporary event queries usually use either IWbemServices::ExecNotificationQuery in C++ applications or SWbemServices.ExecNotificationQuery in scripts and Visual Basic.

事件查询请求事件类的实例,该类指定特定类型的事件,例如 Win32 _ ProcessTraceRegistryKeyChangeEventAn event query requests instances of an event class that specifies a certain type of event, such as Win32_ProcessTrace or RegistryKeyChangeEvent.

当创建 Win32 _ ProcessTrace 的实例时,以下 VBScript 代码示例请求通知。The following VBScript code example requests notification when an instance of Win32_ProcessTrace is created. 当进程启动或停止时,将生成此类的实例。An instance of this class is generated when a process is started or stopped.

若要执行该脚本,请将其复制到名为 event.vbs 的文件中,并使用以下命令行: cscript event.vbsTo execute the script, copy it to a file named event.vbs and use the following command line: cscript event.vbs. 可以通过启动 Notepad.exe 或任何其他进程来查看脚本的输出。You can see output from the script by starting Notepad.exe or any other process. 此脚本在五个进程已启动或停止后停止。The script stops after five processes have started or stopped.

此脚本调用 SWbemServices.ExecNotificationQuery,这是方法的 半同步 版本。This script calls SWbemServices.ExecNotificationQuery, which is the semisynchronous version of the method. 有关通过调用 SWbemServices.ExecNotificationQueryAsync设置异步临时事件订阅的示例,请参阅下一个脚本。See the next script for an example of setting up an asynchronous temporary event subscription by calling SWbemServices.ExecNotificationQueryAsync. 有关详细信息,请参阅 调用方法For more information, see Calling a Method. 此脚本将调用 SWbemEventSource 来获取并处理每个事件的到达。The script calls SWbemEventSource.NextEvent to obtain and process each event as it arrives. 将该脚本保存到扩展名为 .vbs 的文件中,并使用 CScript: cscript file.vbs 在命令行上运行该脚本。Save the script in a file with a .vbs extension and run the script on a command line using CScript: cscript file.vbs.

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" _
    & strComputer & "\root\CIMV2") 
Set objEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM Win32_ProcessTrace")

Wscript.Echo "Waiting for events ..."
i = 0
Do Until i=5
    Set objReceivedEvent = objEvents.NextEvent
    'report an event
    Wscript.Echo "Win32_ProcessTrace event occurred" & VBNewLine _
        & "Process Name = " _
            & objReceivedEvent.ProcessName & VBNewLine _
        & "Process ID = " _
            & objReceivedEvent.Processid & VBNewLine _
        & "Session ID = " & objReceivedEvent.SessionID 
i = i+ 1
Loop

临时事件使用者必须手动启动,且不能在 WMI 重启或操作系统重启之间保持不变。 临时事件使用者只能在事件运行时处理事件。A temporary event consumer can process events only while it is running.

下面的过程介绍如何创建临时事件使用者。The following procedure describes how to create a temporary event consumer.

创建临时事件使用者To create a temporary event consumer

  1. 确定要使用的编程语言。Decide which programming language to use.

    编程语言确定要使用的 API。The programming language determines the API to use.

  2. 开始编写临时事件使用者应用程序的代码,与启动 WMI 应用程序的方式相同。Start coding a temporary event consumer application the same way that you start a WMI application.

    编码的第一步取决于编程语言。The first steps of coding depend on the programming language. 通常,登录到 WMI 并设置安全设置。Typically, you log onto WMI and set up the security settings. 有关详细信息,请参阅 创建 WMI 应用程序或脚本For more information, see Creating a WMI Application or Script.

  3. 定义要使用的事件查询。Define the event query that you want to use.

    若要获取某些类型的性能数据,可能需要使用高性能提供程序提供的类。To obtain some types of performance data, you may need to use classes provided by high-performance providers. 有关详细信息,请参阅 监视性能数据确定要接收的事件的类型以及 通过 WQL 进行查询For more information, see Monitoring Performance Data, Determining the Type of Event To Receive, and Querying with WQL.

  4. 决定进行异步调用或半同步调用,并选择 API 方法。Decide to make either an asynchronous call or an semisynchronous call, and choose the API method.

    异步调用使你可以避免轮询数据的开销。Asynchronous calls allow you to avoid the overhead of polling for data. 但半同步调用提供了类似的性能和更高的安全性。However, semisynchronous calls provide similar performance with greater security. 有关详细信息,请参阅 调用方法For more information, see Calling a Method.

  5. 进行异步或半同步方法调用,并包括事件查询作为 strQuery 参数。Make the asynchronous or semisynchronous method call and include an event query as the strQuery parameter.

    对于 c + + 应用程序,请调用以下方法:For C++ applications, call the following methods:

    对于脚本,请调用以下方法:For scripts, call the following methods:

  6. 编写代码来处理返回的事件对象。Write the code to process the returned event object.

    对于异步事件查询,请将代码放在对象接收器的各种方法或事件中。For asynchronous event queries, put the code in the various methods or events of the object sink. 对于半同步事件查询,每个对象都是在 WMI 获取时返回的,因此,代码应位于处理每个对象的循环中。For semisynchronous event queries, each object is returned as WMI obtains it, so the code should be in the loop that handles each object.

下面的脚本代码示例是 Win32 _ ProcessTrace 脚本的异步版本。The following script code example is an asynchronous version of the Win32_ProcessTrace script. 由于异步操作会立即返回,因此当脚本正在等待事件时,该对话框会保持激活状态。Because asynchronous operations return immediately, a dialog box keeps the script active while it is waiting for events.

该脚本具有 SWbemSink OnObjectReady事件的事件处理程序,而不是调用 SWbemEventSource来接收每个事件。Rather than call SWbemEventSource.NextEvent to receive each event, the script has an event handler for the SWbemSink OnObjectReady event.

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & _
    strComputer & "\root\CIMV2") 
Set EventSink = WScript.CreateObject( _
    "WbemScripting.SWbemSink","SINK_")

objWMIservice.ExecNotificationQueryAsync EventSink, _
    "SELECT * FROM Win32_ProcessTrace WITHIN 10"
WScript.Echo "Waiting for events..."

i = 0
While (True)
    Wscript.Sleep(1000)
Wend

Sub SINK_OnObjectReady(objObject, objAsyncContext)
    Wscript.Echo "Win32_ProcessTrace event has occurred."
    i = i+1
    If i = 3 Then WScript.Quit 0 
End Sub

备注

异步回调(如由子例程处理的回调 SINK_OnObjectReady )允许验证用户向接收器提供数据。An asynchronous callback such as a callback handled by the SINK_OnObjectReady subroutine, allows a nonauthenticated user to provide data to the sink. 为了获得更好的安全性,请使用半同步通信或同步通信。For better security, use either semisynchronous communication or synchronous communication. 有关详细信息,请参阅以下主题:For more information, see the following topics:

使用永久事件使用者Using Permanent Event Consumers

永久事件使用者将运行,直到显式取消其注册,然后在 WMI 或系统重新启动时启动。A permanent event consumer runs until its registration is explicitly canceled, and then starts up when WMI or the system restarts.

永久事件使用者是系统上的 WMI 类、筛选器和 COM 对象的组合。A permanent event consumer is a combination of WMI classes, filters, and COM objects on a system.

以下列表标识了创建永久事件使用者所需的部分:The following list identifies the parts required to create a permanent event consumer:

  • 一个 COM 对象,其中包含实现永久使用者的代码。A COM object containing the code that implements the permanent consumer.
  • 新的永久使用者类。A new permanent consumer class.
  • 永久使用者类的实例。An instance of the permanent consumer class.
  • 包含事件查询的筛选器。A filter that contains the query for events.
  • 使用者与筛选器之间的链接。A link between the consumer and the filter.

有关详细信息,请参阅 始终接收事件For more information, see Receiving Events At All Times.

WMI 提供若干永久使用者。WMI supplies several permanent consumers. 预安装了包含代码的使用者类和 COM 对象。The consumer classes and COM object containing the code are preinstalled. 例如,你可以创建和配置 ActiveScriptEventConsumer 类的实例,以在发生事件时运行脚本。For example, you can create and configure an instance of the ActiveScriptEventConsumer class to run a script when an event occurs. 有关详细信息,请参阅 使用标准使用者监视和响应事件For more information, see Monitoring and Responding to Events with Standard Consumers. 有关使用 ActiveScriptEventConsumer 的示例,请参阅 基于事件运行脚本For an example of using ActiveScriptEventConsumer, see Running a Script Based on an Event.

下面的过程介绍如何创建永久事件使用者。The following procedure describes how to create a permanent event consumer.

创建永久事件使用者To create a permanent event consumer

  1. 使用你正在使用的命名空间注册事件提供程序Register the event provider with the namespace that you are using.

    某些事件提供程序只能使用特定的命名空间。Some event providers can only use a specific namespace. 例如, _ _ InstanceCreationEventWin32 提供程序支持的内部事件,并在默认情况下注册到 \ 根 \ cimv2 命名空间。For example, __InstanceCreationEvent is an intrinsic event that is supported by the Win32 provider and is registered by default with the \root\cimv2 namespace.

    备注

    你可以使用注册中使用的 _ _ EventFilterEventNamespace 属性来创建跨命名空间订阅。You can use the EventNamespace property of the __EventFilter used in the registration to create a cross-namespace subscription. 有关详细信息,请参阅 实现跨命名空间的永久事件订阅For more information, see Implementing Cross-Namespace Permanent Event Subscriptions.

  2. 向事件类所在的命名空间注册事件使用者提供程序Register the event consumer provider with the namespace where event classes are located.

    WMI 使用事件使用者提供程序查找永久性的事件使用者。WMI uses an event consumer provider to find an event consumer that is permanent. 永久事件使用者是接收到事件时 WMI 启动的应用程序。The permanent event consumer is the application that WMI starts when an event is received. 若要注册事件使用者,提供程序将创建 _ _ EventConsumerProviderRegistration的实例。To register event consumer, providers create instances of __EventConsumerProviderRegistration.

  3. 创建类的实例,该类表示要使用的永久事件使用者。Create an instance of the class that represents the permanent event consumer you want to use.

    事件使用者类派生自类 _ _ EventConsumerEvent consumer classes are derived from the class __EventConsumer. 设置事件使用者实例所需的属性。Set the properties that the event consumer instance requires.

  4. 使用 regsvr32 实用工具向 COM 注册使用者。Register the consumer with COM by using the regsvr32 utility.

  5. 创建事件筛选器类 _ _ EventFilter的实例。Create an instance of the event filter class __EventFilter.

    设置事件筛选器实例的必填字段。Set the required fields for the event filter instance. _ _ EventFilter的必填字段是 NameQueryLanguageQueryThe required fields for __EventFilter are Name, QueryLanguage, and Query. Name 属性可以是此类的实例的任何唯一名称。The Name property can be any unique name for an instance of this class. QueryLanguage 属性始终设置为 "WQL"。The QueryLanguage property is always set to "WQL". 查询 属性是一个包含事件查询的字符串。The Query property is a string that contains an event query. 当永久性事件使用者的查询失败时,将生成事件。An event is generated when a permanent event consumer's query fails. 事件的源为 WinMgmt,事件 ID 为10,事件类型为 Error。The event's source is WinMgmt, the event ID is 10, and the event type is Error.

  6. 创建 _ _ FilterToConsumerBinding类的实例,以将逻辑事件使用者与事件筛选器相关联。Create an instance of the __FilterToConsumerBinding class to associate a logical event consumer with an event filter.

    WMI 使用关联来查找与事件关联的事件使用者,该事件与事件筛选器中指定的条件相匹配。WMI uses an association to find the event consumer associated with the event that matches the criteria specified in the event filter. WMI 使用事件使用者提供程序查找要启动的永久事件使用者应用程序。WMI uses the event consumer provider to find the permanent event consumer application to start.