C# 处理进程方法集合

来源:互联网 发布:装修招标网源码 编辑:程序博客网 时间:2024/05/16 02:15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Diagnostics;
using System.Management;


namespace NetBrain_Utility
{
    public class ProcessUtility
    {
        #region public process related methods
        /// <summary>
        /// This is used for test clean up or anytime we need kill EE/IE
        /// </summary>
        /// <param name="processName">To be killed appName</param>
        public static void KillProcess(string processName)
        {
            //Get the  process of all open  
            try
            {
                //Get the  killed  process name
                foreach (Process thisproc in Process.GetProcessesByName(processName))
                {
                    thisproc.Kill();
                }
            }
            catch (Exception Exc)
            {
                Console.WriteLine("Kill process issue:" + Exc.ToString());
            }
        }


        /// <summary>
        /// Check if the process is existing or not by ProcessName
        /// </summary>
        /// <param name="processName"></param>
        /// <returns>exist or not</returns>
        public static bool ExistProcess(string processName)
        {
            //Get the  process of all open 
            bool isExist = false;
            try
            {
                //Get the  killed  process name
                if (Process.GetProcessesByName(processName).Length > 0)
                {
                    isExist = true;
                }
            }
            catch (Exception Exc)
            {
                Console.WriteLine("Launch Netbrain  issue:" + Exc.ToString());
            }
            return isExist;
        }


        /// <summary>
        /// Check if the process is existing or not by ProcessID
        /// </summary>
        /// <param name="processName"></param>
        /// <returns>exist or not</returns>
        public static bool ExistProcess(int processID)
        {
            bool isExist = false;
            try
            {
                if (Process.GetProcessById(processID).Equals(processID))
                {
                    isExist = true;
                }
            }
            catch (Exception Ex)
            {
                Debug.WriteLine("Path scripty running finish:" + Ex.ToString());
            }
            return isExist;
        }
        #endregion


        #region Remote server process


        public static bool KillRemoteProcess(string processName, string RemoteServerIP, string UserName, string passWD)
        {
            bool result = true;
            ConnectionOptions options = new ConnectionOptions();
            options.Username = RemoteServerIP + @"\" + UserName;
            options.Password = passWD;
            ManagementScope scope = new ManagementScope(@"\\" + RemoteServerIP + @"\root\cimv2", options);
            scope.Connect();
            try
            {
                string NameServices = processName;
                WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_Process  WHERE Name=\"" + NameServices + "\"");
                ManagementObjectSearcher find = new ManagementObjectSearcher(scope, query);
                foreach (ManagementObject spooler in find.Get())
                {
                    spooler.Delete();
                }
                if (find.Get().Count > 0)
                {
                    result = false;
                    Console.WriteLine("Kill Process : {0} Failed!", processName);
                }
                else
                {
                    result = true;
                    Console.WriteLine("Kill Process : {0} Success!", processName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return result;
        }


        public static bool StartRemoteProcess(string cmd, string RemoteServerIP, string UserName, string passWD)
        {
            bool result = true;
            ConnectionOptions options = new ConnectionOptions();
            options.Username = RemoteServerIP + @"\" + UserName;
            options.Password = passWD;
            ManagementScope scope = new ManagementScope(@"\\" + RemoteServerIP + @"\root\cimv2", options);
            scope.Connect();
            //object theProcessToRun() = { "C:\Windows\system32\notepad.exe" };
            //ManagementClass theClass = new ManagementClass(@"\\" + RemoteServerIP + @"\root\cimv2:Win32_Process");
            ManagementPath path = new ManagementPath("Win32_Process");
            ManagementClass test = new ManagementClass(scope, path, null);
            object[] methodArgs = { @"C:\Program Files (x86)\NetBrain\autoserver\Search\template\bin\NBSearchEngine.exe C:\Automation\BAT\Path\searchenginedata.xml", null, null, 0 };
            object result1 = test.InvokeMethod("Create", methodArgs);


            return result;
        }


        public static void ResetService(string serviceName)
        {
            ServiceController services = new ServiceController(serviceName);
            if (services.Status.ToString().Contains("Stop"))
            {
                services.Start();
                services.WaitForStatus(ServiceControllerStatus.Running);
                services.Close();
                Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " Changed Stop to start Finished");
            }
            else if (services.CanStop)
            {
                services.Stop();
                services.WaitForStatus(ServiceControllerStatus.Stopped);
                services.Start();
                services.WaitForStatus(ServiceControllerStatus.Running);
                services.Close();
                Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " Reset Finished");
            }
        }
        public static bool RemoteResetService(string serviceName, string RemoteServerIP, string UserName, string passWD)
        {
            ConnectionOptions options = new ConnectionOptions();
            options.Username = RemoteServerIP + @"\" + UserName;
            bool result = true;
            options.Password = passWD;
            ManagementScope scope = new ManagementScope(@"\\" + RemoteServerIP + @"\root\cimv2", options);
            scope.Connect();
            try
            {
                string NameServices = serviceName;
                WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_Service  WHERE Name=\"" + NameServices + "\"");
                ManagementObjectSearcher find = new ManagementObjectSearcher(scope, query);
                foreach (ManagementObject spooler in find.Get())
                {
                    if (spooler.Properties["State"].Value.ToString() == "Running")
                    {
                        object stopresult = spooler.InvokeMethod("StopService", new object[] { });
                        if (stopresult.ToString() == "0")
                        {
                            Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " RemoteResetService Stop Finished");
                        }
                        else
                        {
                            Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " RemoteResetService Stop Failed!!!");
                            result = false;
                            continue;
                        }
                        System.Threading.Thread.Sleep(3000);
                        object startresult = spooler.InvokeMethod("StartService", new object[] { });
                        if (startresult.ToString() == "0")
                        {
                            Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " RemoteResetService Start Finished");
                        }
                        else
                        {
                            Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " RemoteResetService Start Failed!!!");
                            result = false;
                            continue;
                        }
                    }
                    else
                    {
                        object onlystartresult = spooler.InvokeMethod("StartService", new object[] { });
                        //WaitForChangedResult result = new WaitForChangedResult()
                        System.Threading.Thread.Sleep(3000);
                        if (onlystartresult.ToString() == "0")
                        {
                            Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " RemoteResetService Only Start Finished!!!");
                        }
                        else
                        {
                            result = false;
                            Console.WriteLine("TestCase RemoteDB---Service " + serviceName + " RemoteResetService Only Start Failed!!!");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return result;


        }
        /// <summary>
        /// 说明:修改Postgres数据库中config的配置,使其数据库支持远程连接
        /// </summary>
        /// <param name="filepath">要修改的config路径</param>
        /// <param name="findFlag">要查找的字符串信息</param>
        /// <param name="replaceStr">要修改成的字符串</param>
        /// <param name="mode">true-add replacstr; flase-replace str</param>
        public static void ModifyDBRemoteSetting(string filepath, string findFlag, string replaceStr, bool mode = true)
        {
            //int indexid = -1;
            int length = findFlag.Length;
            List<string> context = new List<string>();
            bool isChanged = false;


            using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    string line = sr.ReadLine();
                    while (line != null)
                    {
                        if (line.Contains(replaceStr))
                        {
                            Console.WriteLine("TestCase RemoteDB--" + ' ' + replaceStr + " has been Modified!!!");
                            isChanged = true;
                            break;
                        }
                        else if (line.Contains(findFlag))
                        {
                            if (mode)
                            {
                                context.Add(line);
                                line = replaceStr;
                            }
                            else
                            {
                                line = replaceStr;
                            }


                        }
                        context.Add(line);
                        line = sr.ReadLine();


                    }
                    sr.Close();
                }
                fs.Close();
            }
            // 如果修改过了就不再修改
            if (!isChanged)
            {
                using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        //new StreamWriter()
                        foreach (string line in context)
                        {
                            sw.WriteLine(line);
                        }
                        sw.Close();
                        Console.WriteLine("TestCase RemoteDB--" + ' ' + replaceStr + "  Write Finsh!!!");
                    }
                    fs.Close();
                }
            }
        }


        public static bool RunRemoteCommandFile(string strCommandPath, string RemoteServerIP, string UserName, string passWD)
        {
            try
            {
                ConnectionOptions connOption = new ConnectionOptions();
                connOption.Username = UserName;
                connOption.Password = passWD;


                ManagementPath mngPath = new ManagementPath(@"\\" + RemoteServerIP + @"\root\cimv2:Win32_Process");
                ManagementScope scope = new ManagementScope(mngPath, connOption);
                //ManagementPath mngPath = new ManagementPath(@"\\" + RemoteServerIP + @"\root\cimv2:Win32_Process");
                ObjectGetOptions objOption = new ObjectGetOptions();
                ManagementClass classInstance = new ManagementClass(scope, mngPath, objOption);
                int ProcessId = 0;
                object[] cmdline = { "cmd /c " + strCommandPath, null, null, ProcessId };
                //调用执行命令的方法
                object a = classInstance.InvokeMethod("Create", cmdline);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        public static bool RunRemoteCommand(string strCommand, string RemoteServerIP, string UserName, string passWD)
        {
//            try
//            {
//                ConnectionOptions connOption = new ConnectionOptions();
//                connOption.Username = UserName;
//                connOption.Password = passWD;


//                ManagementPath mngPath = new ManagementPath(@"//" + RemoteServerIP +
//                                            @"/root/cimv2:Win32_Process");
//                ManagementScope scope = new ManagementScope(mngPath, connOption);
//                scope.Connect();
//                ObjectGetOptions objOption = new ObjectGetOptions();
//                ManagementClass classInstance = new ManagementClass(scope, mngPath, objOption);
//                ManagementBaseObject inParams = classInstance.GetMethodParameters("Create");


//                int ProcessId = 0;
//                inParams.SetPropertyValue("CommandLine", strCommand);  
//                object[] cmdline = { "cmd /c " + strCommand, null, null,0 };
//                //schtasks /delete /F /TN idesk3 强制删除计划任务idesk3
//                //object[] cmdline = { "cmd /c schtasks /create /tn idesk3 /tr "+strCommandPath+" /sc once /st 14:31" };
//                classInstance.InvokeMethod("Create", cmdline);


//                ManagementPath path = new ManagementPath("Win32_Process");
//                ManagementClass test = new ManagementClass(scope, mngPath, null);
//                object[] methodArgs = { "cmd /c "+strCommand, null, null, 0 };
//                object result1 = test.InvokeMethod("Create", methodArgs);
//                ManagementBaseObject outParams =
//processClass.InvokeMethod("Create", inParams, null);


//                return true;
//            }
//            catch (Exception)
//            {
//                return false;
//            }
            ConnectionOptions connOption = new ConnectionOptions();
            connOption.Username = UserName;
            connOption.Password = passWD;


            ManagementPath mngPath = new ManagementPath(@"\\" + RemoteServerIP + @"\root\cimv2:Win32_Process");
            ManagementScope scope = new ManagementScope(mngPath, connOption);
            //ManagementPath mngPath = new ManagementPath(@"\\" + RemoteServerIP + @"\root\cimv2:Win32_Process");
            ObjectGetOptions objOption = new ObjectGetOptions();
            ManagementClass classInstance = new ManagementClass(scope, mngPath, objOption);
            int ProcessId = 0;
            object[] cmdline = { "cmd /c " + strCommand, mngPath, null, ProcessId };
            //调用执行命令的方法
            object a = classInstance.InvokeMethod("Create", cmdline);
            return true;
        }
        #endregion


        public static string ExecuteCMD(string command, int seconds)
        {
            string output = ""; //输出字符串
            if (command != null && !command.Equals(""))
            {
                Process process = new Process();//创建进程对象
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe";//设定需要执行的命令
                startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出
                startInfo.UseShellExecute = false;//不使用系统外壳程序启动
                startInfo.RedirectStandardInput = false;//不重定向输入
                startInfo.RedirectStandardOutput = true; //重定向输出
                startInfo.CreateNoWindow = true;//不创建窗口
                //startInfo.RedirectStandardError = true;
                //startInfo.RedirectStandardInput = true;
                //startInfo.RedirectStandardOutput = true;
                //startInfo.UseShellExecute = false;
                //startInfo.CreateNoWindow = true;
                process.StartInfo = startInfo;
                try
                {
                    if (process.Start())//开始进程
                    {
                        if (seconds == 0)
                        {
                            // process.StandardInput.WriteLine(command);
                            process.WaitForExit();//这里无限等待进程结束
                        }
                        else
                        {
                            //process.StandardInput.WriteLine(command);
                            process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒
                        }
                        output = process.StandardOutput.ReadToEnd();//读取进程的输出
                    }
                }
                catch
                {
                }
                finally
                {
                    if (process != null)
                        process.Close();
                }
            }
            return output;
        }
    }
}
原创粉丝点击