Saturday, July 6, 2013

cmdBatch_WMIC_RemoteReboot

 cmdBatch_WMIC_RemoteReboot.docx


Also includes CSharp C# implementation of WMI with System.Management


This set of notes shows how to get information and create a process with a command file and with C#.
This set of notes shows you how to review a class and invoke it - where there are no input parameters but has output parameter



meta: wmi









  • Windows Management Instrumentation The communication layer that Microsoft servers use to interact with Microsoft machines on the network.
    wiki.untangle.com/index.php/Glossary_of_Terms
  • Acronym for Windows Management Instrumentation. WMI is a new management technology allowing scripts to monitor and control managed resources throughout the network. ...
    www.rlmueller.net/Terms.htm




see also “cmdBatch_WMIC_RemoteCPUEtc.docx”

1.    Run any process remotely
2.    Specific restart of target remote box

WMIC.EXE is for windows local and remote info gathering and can be used in a cmd / DOS window – this example shows how to use wmic.exe to reboot/restart your local or a remote computer/box – or run IISRESET or any command remotely.


Example of IISRESET:
@echo off
wmic /node:"MyTargetRemoteBox" process call create "cmd /k IISRESET" > sdresult.txt
echo done. 



Example Testwmic.cmd:

@echo off
wmic /node:"MyTargetRemoteBox" process call create "cmd /k shutdown -r -t 10" > sdresult.txt
echo done.

Output:
C:\aaatest>Testwmic.cmd

done.

C:\aaatest>

The sdresult.txt file from above call:

Executing (Win32_Process)->Create()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
              ProcessId = 1764;
              ReturnValue = 0;
};


Use C# to see information and also create a process on a target machine

cmd window (partial):
...
Service CAPTION = Windows Update
    Service NAME = wuauserv
Service CAPTION = Windows Driver Foundation - User-mode Driver Framework
    Service NAME = wudfsvc
Create process calc.exe.
returnValue = 0
Ready
Press enter to finish...


program.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management; //Also need to set a reference for "System.Management" in the .NET tab

namespace WMICaller
{
    class Program
    {
        static void Main(string[] args)
        {
            TestA();
            CreateProcess_Calc();
            Console.WriteLine("Press enter to finish...");
            Console.ReadLine();
        }
        public static void TestA()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher
    ("SELECT * FROM Win32_Service WHERE Started = TRUE");
            foreach (ManagementObject service in searcher.Get())
            {
                Console.WriteLine("Service CAPTION = " + service["Caption"]);
             Console.WriteLine("    Service NAME = " + service["Name"]);
            }
        }

        private static void CreateProcess_Calc()
        {
            string stringCommandLine = "calc.exe";

            //Connect to the remote computer
            ConnectionOptions co = new ConnectionOptions();
            string stringMachineName = "localhost";
                      


            //Connect to the remote computer optionally with user name and password
            //ConnectionOptions co = new ConnectionOptions();
            //co.Username = textUserID.Text;
            //co.Password = textPassword.Text;



            //Point to machine
            System.Management.ManagementScope ms = new System.
                Management.ManagementScope("\\\\" +
                stringMachineName + "\\root\\cimv2", co);


            //get process path
            ManagementPath path = new ManagementPath("Win32_Process");

            //Get the object on which the method will be invoked
        ManagementClass processClass = new ManagementClass
                (ms, path, null);

            //Status
            Console.WriteLine("Create process " + stringCommandLine + ".");

            //Create an array containing all arguments for the method


            /*
                CommandLine - [in] Command line to execute. The system adds a null character to the command line, trimming the string if necessary, to indicate which file was actually used.
                CurrentDirectory - [in] Current drive and directory for the child process. The string requires that the current directory resolves to a known path. A user can specify an absolute path or a path relative to the current working directory. If this parameter is NULL, the new process will have the same path as the calling process. This option is provided primarily for shells that must start an application and specify the application's initial drive and working directory.
                ProcessStartupInformation - [in] The startup configuration of a Windows process. For more information see Win32_ProcessStartup.
                ProcessId - [out] Global process identifier that can be used to identify a process. The value is valid from the time the process is created until the time the process is terminated.
          */


            object[] methodArgs = { stringCommandLine, null, null, 0 };

            ManagementOperationObserver observer = new
    ManagementOperationObserver();
            MyHandler completionHandlerObj = new MyHandler();
            observer.ObjectReady += new ObjectReadyEventHandler
                (completionHandlerObj.Done);
           

            //Execute the method
            processClass.InvokeMethod(observer, "Create", methodArgs);
           
            //wait until invoke method is complete or 5 sec timeout
            int intCount = 0;
            while (!completionHandlerObj.IsComplete)
            {
                if (intCount > 10)
                {
                    Console.WriteLine("Create process timed out.",
                        "Terminate Process Status");
                    break;
                }
                //wait 1/2 sec.
                System.Threading.Thread.Sleep(500);

                //increment counter
                intCount++;
            }

            if (intCount != 10)
            {
                //InvokeMethod did not time out
                //check for error
                if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
                {
                    Console.WriteLine("returnValue = {0}", completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString());
                }
                else
                {
                    Console.WriteLine("Error creating new process - Create New Process");
                }
            }

            //Status
            Console.WriteLine("Ready");
           
        }
    }
    /// <summary>
    /// MyHandler class handle notification
    /// when InvokeMethod call is complete
    /// </summary>
    public class MyHandler
    {
        private bool isComplete = false;
        private ManagementBaseObject returnObject;

        /// <summary>
        /// Trigger Done event when InvokeMethod is complete
        /// </summary>
        public void Done(object sender, ObjectReadyEventArgs e)
        {
            isComplete = true;
            returnObject = e.NewObject;
        }


        /// <summary>
        /// Get property IsComplete
        /// </summary>
        public bool IsComplete
        {
            get
            {
                return isComplete;
            }
        }

        /// <summary>
        /// Property allows accessing the result
        /// object in the main function
        /// </summary>
        public ManagementBaseObject ReturnObject
        {
            get
            {
                return returnObject;
            }
        }

    }

}



No comments:

Post a Comment