Friday, November 5, 2010

Using ASP.NET C# WMI to kill process, & start/stop services


Earlier I had written an RPK application that is essentially a remote process killer, and remotely kills processes using WMI. Previously I had also created an application that uses WMI to change a password for service, and starts the service. I had to integrate the two into an ASP.NET application that did this. Here is the segment of code that takes input from a text box like a command interpreter and based on the sequence of code, either starts/stops a service or kills a given process:




    void ExeCommand(string x)
    {
        Label1.ForeColor = Color.Maroon;
        Label1.Text = "<b>Error:</b>"  +
            "<br /> Pleasse check the syntax of the command. <br />" +
        "The appropriate command should be: <br />stop service_name or " +
        "start service_name or <br /> kill process_name";
        
        
        
        try
        {
            
            string[] words = x.Split(' ');


            if (words[0].ToString().ToLower() == "start" || words[0].ToString().ToLower() == "stop")
            {
                Label1.ForeColor = Color.Black;
                Label1.Text = "Sorry! No Services Found by that description!";               
                ConnectionOptions co = new ConnectionOptions();
                co.Username = txtUsername.Text;
                co.Password = txtPassword.Text;
                co.Impersonation = ImpersonationLevel.Impersonate;
                co.EnablePrivileges = true;
                co.Authentication = AuthenticationLevel.PacketPrivacy;


                string queryStr = "select * from Win32_Service where Name like '";
                queryStr += words[1].ToString().Replace('\\', '%');
                queryStr += "'";


                string temp1 = txtServer.Text;
                System.Management.ManagementScope ms =
                    new System.Management.ManagementScope("\\\\" + temp1 + "\\root\\cimv2", co);


                ObjectQuery oQuery = new ObjectQuery(queryStr);


                //Execute the query  
                ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(ms, oQuery);


                //Get the results
                ManagementObjectCollection oReturnCollection = oSearcher.Get();


                foreach (ManagementObject oReturn in oReturnCollection)
                {
                    string serviceName = oReturn.GetPropertyValue("Name") as string;


                    string fullServiceName = "Win32_Service.Name='";
                    fullServiceName += serviceName;
                    fullServiceName += "'";






                    if (words[0].ToLower().ToString() == "stop" || words[0].ToLower().ToString() == "stopservice")
                    {
                        Label1.Text = "<br />Stopping Service <b>" +
                             serviceName.ToString() + "</b>";
                        oReturn.InvokeMethod
                          ("StopService", new object[] { null });
                        Label1.Text += "<br /><b>" + serviceName + "</b> service has been stopped!";
                    }


                    if (words[0].ToLower().ToString() == "start" || words[0].ToLower().ToString() == "startservice")
                    {
                        Label1.Text = "<br />Starting Service <b>" +
                         serviceName.ToString() + "</b>";
                        oReturn.InvokeMethod
                         ("StartService", new object[] { null });
                        Label1.Text += "<br /><b>" + serviceName + "</b> service has been started!";
                    }


                    oReturn.Dispose();


                }
              }  
                else
              {
                if (words[0].ToString().ToLower() == "kill")
                {
                    Label1.ForeColor = Color.Black;
                    Label1.Text = "Sorry! No Processes Found by that description!";               
                    ConnectionOptions co = new ConnectionOptions();
                co.Username = txtUsername.Text;
                co.Password = txtPassword.Text;
                co.Impersonation = ImpersonationLevel.Impersonate;
                co.EnablePrivileges = true;
                co.Authentication = AuthenticationLevel.PacketPrivacy;


                string queryStr = "select * from Win32_Process where Name like '";
                queryStr += words[1].ToString().Replace('\\', '%');
                queryStr += "'";


                string temp1 = txtServer.Text;
                System.Management.ManagementScope ms =
                    new System.Management.ManagementScope("\\\\" + temp1 + "\\root\\cimv2", co);


                ObjectQuery oQuery = new ObjectQuery(queryStr);


                //Execute the query  
                ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(ms, oQuery);


                //Get the results
                ManagementObjectCollection oReturnCollection = oSearcher.Get();


                foreach (ManagementObject oReturn in oReturnCollection)
                {
                    Label1.Text = "<br />Terminating Process <b>" +
                             oReturn.ToString() + "</b><br />";
                    string[] argList = new string[] { string.Empty };
                    object[] obj = new object[] { 0 };
                    oReturn.InvokeMethod("Terminate", obj);
                }
                }
              }


        }
        catch (Exception ex)
        {
            Label1.ForeColor = Color.Maroon;
            Label1.Text = "<b>Error:</b>" + ex.Message +
                "<br /> Pleasse check the syntax of the command. <br />" + 
            "The appropriate command should be: <br />stop service_name or " + 
            "start service_name or <br /> kill process_name";
        }
    }

No comments:

Post a Comment