Section B.4. Authentication with WMI


B.4. Authentication with WMI

So far, the examples we've shown assume that the caller of the script has the necessary rights to access the WMI information on the target computer. In most cases in which you are trying to automate a task, that may not be the case. Luckily, using alternate credentials in WMI is very straightforward.

Previously, to connect to a WMI namespace, we would have used the following:

strComputer = "srv01.rallencorp.com" set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

But let's say that the person calling the script does not have any privileges on srv01. We must now use the following:

strComputer = "srv01.movie.edu" strUserName = "administrator" strPassword = "password" set objLocator = CreateObject("WbemScripting.SWbemLocator") set objWMI = objLocator.ConnectServer(strComputer, "root\cimv2", _                                       strUserName, strPassword)

We've replaced the single call to GetObject with a call to CreateObject to instantiate a WbemScripting.SWbemLocator object. The SWbemLocator object has a method called ConnectServer, which allows us to specify the target machine, username, and password.[1] We can then use the object returned from ConnectServer to get the instances of a class, perform a WQL search, or carry out any other function.

[1] Obviously, it is less than ideal to include passwords in plain text scripts. An alternative would be to require the user to use the runas command to authenticate as the privileged user, or if you plan on running the script via Scheduled Tasks, to provide credentials when you configure the task.



Windows Server Cookbook
Windows Server Cookbook for Windows Server 2003 and Windows 2000
ISBN: 0596006330
EAN: 2147483647
Year: 2006
Pages: 380
Authors: Robbie Allen

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net