Exemplo n.º 1
0
        /// <summary>
        /// процесс установки из установочного exe файла
        /// </summary>
        public void exeInstallProcess(Object stateInfo)
        {
            pingSender  = new Ping();
            pingOptions = new PingOptions();
            pingOptions.DontFragment = true;
            int    timeout      = 120;
            string remoteFolder = String.Empty;

            try
            {
                PingReply reply = pingSender.Send(remoteMachine, timeout);

                if (reply.Status != IPStatus.Success)
                {
                    entry.Status = Properties.Resources.HostNotAvailable;
                }
                else
                {
                    try
                    {
                        //получения токена безопасности для получения доступа к административному ресурсу C$ на который будет копироваться дистрибутив
                        ImpersonateUser iU = new ImpersonateUser();
                        if (userName.Length > 0)
                        {
                            iU.Impersonate(remoteMachine, userName, password);
                        }

                        entry.Status = Properties.Resources.CopyFiles;
                        remoteFolder = @"\\" + remoteMachine + @"\c$\" + randomFolderName + @"\";

                        string sourceFilePath = filePath;

                        string fileName            = Path.GetFileName(sourceFilePath);
                        string destinationFilePath = System.IO.Path.Combine(@"c:\" + randomFolderName + @"\", fileName);

                        //пакет распространяется из одного файла или из директории

                        System.IO.Directory.CreateDirectory(remoteFolder);
                        if (oneFile)
                        {
                            string remoteFile = System.IO.Path.Combine(remoteFolder, fileName);
                            System.IO.File.Copy(sourceFilePath, remoteFile, true);
                        }

                        else
                        {
                            string localFolder = Path.GetDirectoryName(filePath);
                            CopyDir(localFolder, remoteFolder);
                        }

                        if (iU != null)
                        {
                            iU.Undo();
                        }


                        //подключение к службе WMI и запуск процесса установки с параметрами
                        entry.Status = Properties.Resources.Instalation;
                        ConnectionOptions connOptions = new ConnectionOptions();
                        if (userName.Length > 0)
                        {
                            connOptions.Username = userName;
                            connOptions.Password = password;
                        }
                        connOptions.Impersonation    = ImpersonationLevel.Impersonate;
                        connOptions.EnablePrivileges = true;
                        ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2",
                                                                                     remoteMachine), connOptions);
                        manScope.Connect();
                        ObjectGetOptions objectGetOptions = new ObjectGetOptions();

                        ManagementPath managementPath = new ManagementPath("Win32_Process");

                        ManagementClass      processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
                        ManagementBaseObject inParams     =
                            processClass.GetMethodParameters("Create");

                        // добавление входных параметров
                        inParams["CommandLine"] = destinationFilePath + " " + exeOptions;

                        // выполнение метода установки и получение кода события возвращенного методом
                        ManagementBaseObject outParams =
                            processClass.InvokeMethod("Create", inParams, null);
                        installProcessID = (int)(uint)outParams.Properties["processId"].Value;

                        WqlEventQuery query = new WqlEventQuery(
                            "SELECT * FROM Win32_ProcessStopTrace WHERE ProcessID = " + installProcessID);

                        ManagementEventWatcher watcher  = new ManagementEventWatcher(manScope, query);
                        ManagementBaseObject   eventObj = watcher.WaitForNextEvent();
                        watcher.EventArrived += new EventArrivedEventHandler(this.ProcessStopEventArrived);

                        //из кода события получаем соответствующее текстовое сообщение и записываем в запись о компутере
                        entry.Status = new Win32Exception((int)installProcessExitCode).Message;

                        System.IO.Directory.Delete(Path.GetDirectoryName(remoteFolder), true);
                    }
                    catch (FileNotFoundException ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    //при установке некоторых программ например фаерволов, на короткое время разрываются все сетевые подключения
                    //это событие вызывает нижеследующее исключение
                    catch (System.Runtime.InteropServices.COMException ex)
                    {
                        entry.Status = ex.Message;
                    }

                    //все остальные исключения
                    catch (Exception ex)
                    {
                        entry.Status = ex.Message;
                    }
                }
            }
            catch (PingException ex)
            {
                entry.Status = ex.Message;
            }
            catch (SocketException ex)
            {
                entry.Status = ex.Message;
            }

            finally
            {
                if (Directory.Exists(remoteFolder))
                {
                    System.IO.Directory.Delete(Path.GetDirectoryName(remoteFolder), true);
                }
                doneEvent.Set();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// процесс установки msi пакета
        /// </summary>
        public void installProcess(Object stateInfo)
        {
            pingSender  = new Ping();
            pingOptions = new PingOptions();
            pingOptions.DontFragment = true;
            int    timeout      = 120;
            string remoteFolder = String.Empty;

            try
            {
                PingReply reply = pingSender.Send(remoteMachine, timeout);

                if (reply.Status != IPStatus.Success)
                {
                    entry.Status = "Узел недоступен";
                }
                else
                {
                    try
                    {
                        ImpersonateUser iU = new ImpersonateUser();
                        if (userName.Length > 0)
                        {
                            if (userName.IndexOf('\\') > -1)
                            {
                                char[]   splitters  = { '\\' };
                                string[] userDomain = userName.Split(splitters);
                                iU.Impersonate(userDomain[0], userDomain[1], password);
                            }

                            else
                            {
                                iU.Impersonate(String.Empty, userName, password);
                            }
                        }
                        entry.Status = Properties.Resources.CopyFiles;
                        remoteFolder = @"\\" + remoteMachine + @"\c$\" + randomFolderName + @"\";

                        string sourceFilePath = filePath;

                        string fileName            = Path.GetFileName(sourceFilePath);
                        string destinationFilePath = System.IO.Path.Combine(@"c:\" + randomFolderName + @"\", fileName);

                        //пакет распространяется из одного файла или из директории

                        System.IO.Directory.CreateDirectory(remoteFolder);
                        if (oneFile)
                        {
                            string remoteFile = System.IO.Path.Combine(remoteFolder, fileName);
                            System.IO.File.Copy(sourceFilePath, remoteFile, true);
                        }

                        else
                        {
                            string localFolder = Path.GetDirectoryName(filePath);
                            CopyDir(localFolder, remoteFolder);
                        }

                        if (iU != null)
                        {
                            iU.Undo();
                        }

                        //подключение к службе WMI и запуск метода установки
                        entry.Status = Properties.Resources.Instalation;
                        ConnectionOptions connOptions = new ConnectionOptions();
                        if (userName.Length > 0)
                        {
                            connOptions.Username = userName;
                            connOptions.Password = password;
                        }
                        connOptions.Impersonation    = ImpersonationLevel.Impersonate;
                        connOptions.EnablePrivileges = true;
                        ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2",
                                                                                     remoteMachine), connOptions);
                        manScope.Connect();
                        ObjectGetOptions objectGetOptions = new ObjectGetOptions();

                        ManagementPath managementPath = new ManagementPath("Win32_Product");

                        ManagementClass      processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
                        ManagementBaseObject inParams     =
                            processClass.GetMethodParameters("Install");

                        // добавление входных параметров
                        inParams["AllUsers"]        = true;
                        inParams["Options"]         = optionRestart + " " + exeOptions;
                        inParams["PackageLocation"] = destinationFilePath;//+ " " + optionRestart;

                        // выполнение метода установки и получение кода события возвращенного методом
                        ManagementBaseObject outParams =
                            processClass.InvokeMethod("Install", inParams, null);



                        errorCode = (uint)(outParams.Properties["ReturnValue"].Value);
                        //из кода события получаем соответствующее текстовое сообщение и записываем в запись о компутере
                        entry.Status = new Win32Exception((int)errorCode).Message;
                    }
                    catch (FileNotFoundException ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    //при установке некоторых программ например фаерволов, на короткое время разрываются все сетевые подключения
                    //это событие вызывает нижеследующее исключение
                    catch (System.Runtime.InteropServices.COMException ex)
                    {
                        entry.Status = ex.Message;
                    }

                    //все остальные исключения
                    catch (Exception ex)
                    {
                        entry.Status = ex.Message;
                    }
                }
            }
            catch (PingException ex)
            {
                entry.Status = ex.Message;
            }
            catch (SocketException ex)
            {
                entry.Status = ex.Message;
            }

            finally
            {
                if (Directory.Exists(remoteFolder))
                {
                    System.IO.Directory.Delete(Path.GetDirectoryName(remoteFolder), true);
                }
                doneEvent.Set();
            }
        }