Using WMI Scripting - Dell

36 downloads 746 Views 544KB Size Report
Windows Management Instrumentation (WMI), which offers administrators a rich management ... The examples in this article use VBScript as the scripting lan-.
066-70 Shetty.qxd

6/16/04

2:49 PM

Page 66

SYSTEMS MANAGEMENT

Using WMI Scripting for System Administration Windows Management Instrumentation (WMI), which offers administrators a rich management scripting tool set, is an integral part of the Microsoft Windows family of operating systems—which includes Microsoft Windows 2000, Windows XP, and Windows Server™ 2003. This article introduces WMI, explains basic scripting techniques, and provides examples for automating systems management processes using Dell™ OpenManage™ tools. BY SUDHIR SHETTY

indows® Management Instrumentation (WMI) is the

W

WMI. Examples of standard Windows resources that can

underlying management technology for Microsoft®

be managed using WMI include computer systems, disks,

Windows operating systems. Based on industry standards,

peripheral devices, event logs, files, folders, file sys-

WMI helps enable consistent, uniform management con-

tems, networking components, operating system sub-

trol and monitoring of systems throughout an enterprise.

systems, performance counters, printers, processes,

WMI allows system administrators to query, change, and

registry settings, security, services, Microsoft Active

monitor configuration settings on desktop and server sys-

Directory® directory service, Windows Installer, and

tems, applications, networks, and other components of

Windows Driver Model device drivers. WMI data providers

the IT infrastructure. System administrators can create a

access the managed resources using the appropriate

wide range of systems management and monitoring scripts

application programming interfaces (APIs) and expose

that work with WMI using the WMI scripting library.

the data to the WMI infrastructure using a standardsbased, object-oriented data model.

Overview of WMI architecture

The operating system is bundled with standard

Figure 1 shows the three primary layers of the WMI archi-

providers for accessing standard operating-system

tecture: WMI data providers, WMI management infra-

resources such as processes, registry settings, and so

structure, and WMI consumers.

forth. In addition, WMI enables software developers to add and integrate additional providers that expose

66

WMI data providers

data and management functionality unique to their

The data providers retrieve information from managed

products. For example, Dell provides a Common Infor-

resources. A managed resource is a logical or physical

mation Model (CIM) provider, which exposes addi-

component that can be accessed and managed using

tional asset information through WMI. The Dell™

POWER SOLUTIONS

June 2004

066-70 Shetty.qxd

6/16/04

2:49 PM

Page 67

SYSTEMS MANAGEMENT

about the C: drive, D: drive, and so on, can be retrieved by query-

WMI consumers

ing the CIMOM. Attributes, or properties, of this class, such as

WMI script

FreeSpace, Name, and Size, can be queried remotely. Because the WMI scripting library

operational state of most resources changes frequently, information is typically read on demand to ensure that up-to-date

WMI management infrastructure

CIMOM (WMI service)

information is retrieved. CIM repository

CIM classes are organized into namespaces. Each namespace contains a logical group of related classes representing a specific area

WMI data providers

of management. WMI providers

WMI consumers WMI consumers are management applications or scripts that

Managed resources or managed objects (applications, devices, systems)

access and control management information available through the WMI infrastructure.

Introduction to scripting

Figure 1. Three primary layers of the WMI architecture

Windows scripting provides a rich environment in which administrators can develop scripts. Scripts can access Component Object OpenManage™ Server Administrator CIM Reference Guide

Model (COM) objects that support automation or standard access

contains additional information on the data model supported

methodologies. This capability enables scripts to access COM-based

by this provider. The documentation is available online at

technologies, such as WMI or Active Directory Service Interfaces

http://docs.us.dell.com/docs/software/svradmin.

(ADSI), to manage Windows subsystems.

WMI management infrastructure

guage because of its widespread usage. Other scripting tech-

The WMI infrastructure consists of the Common Information Model

nologies (for example, Microsoft JScript® development software)

Object Manager (CIMOM), which manages the interaction between

that support COM automation can also be used to access WMI

The examples in this article use VBScript as the scripting lan-

consumers and data providers. All WMI requests and data flow

objects. Available on Windows XP and Windows Server™ 2003 is

through the CIMOM. The WMI service acts as the CIMOM and is

a command-line tool for accessing WMI information, called WMIC

similar to other operating system services. For example, it can be

(Windows Management Instrumentation Command-line).

stopped and started using the following commands:

Figure 2 provides a simple example of a WMI script, which lists the logical disk information for the local computer. To invoke

net stop winmgmt net start winmgmt strComputer = "."

Management applications, administrative tools,

Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & _

and scripts make requests to the CIMOM to retrieve

"\root\cimv2")

data, subscribe to events, or perform managementrelated tasks. The CIMOM retrieves the provider and

Set colDisks = objWMIService.ExecQuery _ ("SELECT * FROM Win32_LogicalDisk")

class information to service the request from the CIM repository. The CIMOM uses the information obtained from the CIM repository to pass the consumer request to the appropriate WMI provider. The CIM repository holds the schema, or object repository, that models the managed environment. CIM uses a rich object-oriented data model and the notion of classes to represent information about man-

Const CONVERT_TO_MB = 1048576 For each objDisk in colDisks WScript.Echo "Name:" & objDisk.Name WScript.Echo "Size(MB):" & Int(objDisk.Size / CONVERT_TO_MB) WScript.Echo "Free Space (MB):" & _ Int(objDisk.FreeSpace /CONVERT_TO_MB) Next

aged resources. For example, a Win32_LogicalDisk class represents logical disk information on a computer. Instances of this class, such as information www.dell.com/powersolutions

Figure 2. Sample WMI script for listing logical disk information

POWER SOLUTIONS

67

066-70 Shetty.qxd

6/16/04

2:49 PM

Page 68

SYSTEMS MANAGEMENT

the script, save the listing into a file called disk.vbs and run the

Based on industry

network of Dell systems in the enterprise. Examples in this sec-

following command:

standards, WMI helps

tion illustrate the remote execution of Dell OpenManage Server

C:> cscript disk.vbs

enable consistent, uniform with the Windows Script Host (WSH) and is used for running scripts.

management control and

Note that the script in Figure 2 can be adapted to access a variety of information about managed resources. Information about

PowerEdge™ server. To remotely execute other processes on target

monitoring of systems

managed resources can be viewed by downloading WMI administrative tools from http://www.microsoft.com/downloads/details.aspx?

Administrator command-line interface (CLI) commands on a Dell

Cscript.exe is a console-based scripting host that is packaged

nodes, administrators can customize these examples. A complete

throughout an enterprise.

FamilyId=6430F853-1120-48DB-8CC5-F2ABDC3ED314&display-

command reference can be found in the Dell OpenManage Server

lang=en. CIM Studio, which is bundled in the WMI administrative

Administrator Command-Line Interface User’s Guide, which is avail-

tool set, lets administrators view class information in the CIM repos-

able on the documentation CD that ships with every PowerEdge

itory. For other sample scripts that perform a variety of useful system

server or online at http://docs.us.dell.com/docs/software/svradmin.

administration tasks, visit Dell Power Solutions online at

Figure 4 shows an example script that executes a process on a

http://www.dell.com/magazines_extras.

remote system. To invoke the script on a remote server, called

Figure 3 lists additional useful tasks that system administrators can script.

MachineA in this example, save the preceding listing into a file called remote.vbs and run the following command:

Scripting to execute processes on remote Dell systems

C:> cscript remote.vbs MachineA "omreport system

Administrators can write scripts to execute processes on remote

esmlog –outa c:\%COMPUTERNAME%_ESMLOG.TXT"

systems, a technique that can be used in many ways to manage a The script in Figure 4 initiates the remote execution of the Windows entity

Description

WMI-scriptable usage model

process and does not wait for the process to complete. Executing

Event logs

Provide a repository of activities on a computer

and query event logs • Retrieve event log properties • Configure • Back up and clear event logs printers and print jobs • Monitor printer connections on • Manage client systems

the script exports the Embedded Server Management (ESM) log

Printers

Manage printers in the enterprise

Registry

Contains configuration settings for the operating system, applications, and services under Windows

Files/folders

Contain valuable enterprise data

Disks and file system

Manage disks and file systems to ensure continued access to data

Active Directory users

Manage user account information in Active Directory

Computer asset information

Contains an inventory of hardware information, including the operating system and other software installed on the remote computer

Computer roles

Manage computers and computer roles in Active Directory

Processes

Manage running instances of an application or an executable file

new registry entries • Create and update registry entries • Delete • Back up the registry files and folders (create, delete, • Manage and update) files • Enumerate shares • Manage • Monitor the file system disk partitions • Manage logical disk drives • Manage • Manage disk space user accounts • Create user accounts • Manage • Delete user accounts upgrade, and remove software • Install, system information, such as • Retrieve operating system, memory, and



disk space Manage computer startup and recovery settings

manage, and delete computer • Create, accounts in Active Directory Manage the roles assigned to computers • processes • Monitor and terminate processes • Create Enumerate additional process properties •

into a text file on the remote target. This capability offers a rich set of possibilities for the remote scripting of PowerEdge Servers using Server Administrator CLI commands, including:



omconfig: Configures values using the CLI. Administrators

can use specific values for warning thresholds on components or prescribe what action a system should take when a certain warning or failure event occurs. Administrators can also use the omconfig command to assign specific values to a system’s asset information parameters, such as the purchase price of the system, the system’s asset tag, or the system’s location.



omdiag: Runs diagnostic tests against system hardware to iso-

late problems.

• •

omhelp: Displays short help text for CLI commands.



omupdate: Installs the latest update packages for the system’s

omreport: Produces reports of a system’s management

information. BIOS, firmware, and drivers. Administrators can run sequences of these commands using a batch file on a remote managed node. For a sample script that executes a batch file on a remote node, visit Dell Power Solutions online

Figure 3. Examples of scriptable administrative tasks

68

POWER SOLUTIONS

at http://www.dell.com/magazines_extras. June 2004

066-70 Shetty.qxd

6/16/04

2:49 PM

Page 69

SYSTEMS MANAGEMENT

strComputer = WScript.Arguments.Item(0) strCommand = WScript.Arguments.Item(1)

Wizard on the management station to per-

Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & _ "\root\cimv2:Win32_Process")

Security considerations

form the update during off-peak hours.

WMI scripts run in the security context of the administrator running the script. To run

errReturn = objWMIService.Create(strCommand,null,null,intProcessID) if errReturn = 0 Then Wscript.Echo strCommand & " was started with a process ID of " _ & intProcessID & "." Else Wscript.Echo strCommand & " could not be started due to error " & _ errReturn & "." End If

scripts on a remote computer, a user needs administrative access on the remote system, thus helping to prevent malicious individuals from running destructive scripts on a remote server. Remote WMI scripting leverages Distributed COM (DCOM) for interacting with the WMI service running on the remote system. The scripts in this article set the impersonation level to “impersonate.” This setting

Figure 4. Sample WMI script for executing a remote process

implies that the WMI service uses the

Performing a remote software update under Dell OpenManage

administrator’s security context to perform the requested operation.

Administrators can perform a remote software update for BIOS,

If the administrator’s security credentials are not adequate, errors

firmware, and drivers by using the omupdate command or by using

such as “Access Denied” will occur when running the script. WMI provides a rich security infrastructure that can be config-

a Dell Update Package. omupdate CLI command. To execute the omupdate command,

ured on a per-namespace basis. By default, the administrator’s group has full control of WMI on both local and remote computers, and

an administrator would invoke the following:

users in other groups do not have remote access to the computers. omupdate biosupdate path="\\network_share\file_name "

To view a computer’s security settings, invoke wmimgmt.msc from the command prompt, view the properties of the root node, and look

This sample command refers to the network share where the update file resides. In the absence of a network share, administrators can copy the file to a temporary directory on the local system before performing the update. Dell Update Package. Another option is to copy the Dell Update Package, which is a self-contained .exe file, onto the remote system. The .exe file can be directly executed on the remote node by passing its command-line arguments for a silent installation of the package and rebooting the system, if necessary. The WMI script listed in Figure 5 illustrates a remote software update that passes in the computer name and the name of the Dell Update Package. In the script, note that the Dell Update Package is invoked with the /s /r option to perform a silent update and

strComputer = WScript.Arguments.Item(0) strDupFile = WScript.Arguments.Item(1) '* First copy the Dell Update Package to the remote system Set objFSO=CreateObject("Scripting.FileSystemObject") ObjFSO.CopyFile strDupFile, "\\" & strComputer & "\C$\tmp\" & _ strDupFile '* Launch the process on the remote system Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & _ "\root\cimv2:Win32_Process") strCommand = "C:\tmp\" & strDupFile & " /s /r" errReturn = objWMIService.Create(strCommand,null,null,intProcessID) if errReturn = 0 Then Wscript.Echo strCommand & " was started with a process ID of " _ & intProcessID & "." Else Wscript.Echo strCommand & " could not be started due to error " & _ errReturn & "." End If

reboot of the system, if necessary. For a scheduled update, administrators can use the Windows Scheduled Task www.dell.com/powersolutions

Figure 5. Sample WMI script for a remote software update

POWER SOLUTIONS

69

066-70 Shetty.qxd

6/16/04

2:49 PM

Page 70

SYSTEMS MANAGEMENT

PASSING ARGUMENTS THROUGH A TEXT FILE Several scripts in this article involve passing arguments through the command line. An alternative is to pass arguments as a text file. For example, to perform a software update on a set of PowerEdge 2650 servers, administrators can export an external database to list several servers in a text file, such as Server1, Server2, and Server3. This text file can then be passed as a command-line argument to the example script listed in Figure A. Set objArgs = Wscript.Arguments Const ForReading = 1 Set objDictionary = CreateObject("Scripting.Dictionary") Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile(objArgs(0), ForReading) '* Read the file which contains a list of machines, one per line I = 0 Do While objTextFile.AtEndOfStream True StrNextLine = objTextFile.ReadLine objDictionary.Add I, strNextLine I = I + 1 Loop '* For each machine, retrieve the number of services running on that machine For Each objItem in objDictionary strComputer = objDictionary.Item(objItem) Wscript.Echo "Accessing remote machine" & strComputer Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & _ "\root\cimv2") Set colServices = objWMIService.ExecQuery _ ("SELECT * FROM Win32_Service") Wscript.Echo strComputer, colServices.count Next

Figure A. Sample WMI script for reading arguments from a text file

at the security tab of the dialog box. Administrators can alter secu-

wmisdk/wmi/scripting_access_to_wmi.asp) and the book Microsoft

rity settings at the namespace level and grant different permissions

Windows 2000 Scripting Guide by the Microsoft Windows Resource

(remote access, method execution, or write) to different sets of

Kit Scripting Team provide additional valuable information about

users (domain or local).

WMI and scripting.

A powerful tool for performing administrative tasks WMI scripting is designed to provide a powerful mechanism that helps system administrators to perform remote administration tasks. The techniques presented in this article help provide an introduction to the power of WMI scripting. The Microsoft Web page “Scripting Access to WMI” (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/

70

POWER SOLUTIONS

Sudhir Shetty ([email protected]) is a member of the Enablement Technologies team at Dell, working on systems management console solutions. He has more than 10 years of experience in designing and developing software components for user interfaces; database access; and networking in application areas such as systems management, systems prototyping and simulation, and tiered, distributed computing. Sudhir has an M.S. in Computer Science from The University of Texas at Austin.

June 2004