Wednesday, October 31, 2007

WMI Queries on Remote Machines

Windows management instrumentation (WMI) can be used to access system management data across remote machines. You can use this to get status and configuration information on windows machines listening on the network. The classes found in the System.Management namespace helps developers to write code to access these information quickly.

The following example shows how to access LogicalMemoryConfiguration data on a remote machine.

using System;
using System.Net;
using System.Management;

namespace WMIonRemoteMachine
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the Adminstrator's Username and Password
            ConnectionOptions co = new ConnectionOptions();
            co.Username = "Administrator";
            co.Password = "password#xyz";

            //Connect to the default namespace on Remote Machine
            ManagementScope scope = new ManagementScope(@"\\[REMOTE MACHINE]\root\cimv2", co);   
       
            SelectQuery query = new SelectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

            foreach (ManagementObject mObj in searcher.Get())
            {
                foreach (System.Management.PropertyData property in mObj.Properties)
                    System.Console.WriteLine(property.Name.PadLeft(25,' ') + ": " + property.Value);
            }            
            Console.ReadLine();
        }
    }
}

OUTPUT 

  AvailableVirtualMemory: 1405028
                          Caption: Logical Memory Configuration
                     Description: Logical Memory Configuration
                             Name: LogicalMemoryConfiguration
                       SettingID: LogicalMemoryConfiguration
       TotalPageFileSpace: 2523064
     TotalPhysicalMemory: 1046512
        TotalVirtualMemory: 3569576

 

The username and password supplied in the above code should belong to an account that is a member of Administrator Group on the remote machine. If the ConnectionOptions is not set then the namespace residing on the Local System is accessed.

The default WMI namespace or schema "\root\cimv2" is queried to retrieve common system management information. WMI implements the Common Information Model (CIV) schema proposed by Distributed Management Task Force (DMTF).

Remote connections in WMI are affected by Firewall. It blocks all data requests from remote machines. If a connection fails, an exception of type System.Runtime.InteropServices.COMException is thrown in System.Management with an error message "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)". So make sure that the firewall settings are configured to allow these connections.

No comments: