Пример #1
0
        private void SSHCommandThread(IP selectedIP, string command, string commandinresult, string login, string password, bool showWindow = true, bool addToListBoxTask = true)
        {
            Thread runThread = new Thread(new ThreadStart(() =>
            {
                ItemListBoxTask curItemLBT = new ItemListBoxTask()
                {
                    IPOrName = selectedIP.NBNameOrIP(), Description = $"Выполняется {command}", CVZNumber = $"ЦВЗ№{SelectedTT.NumberCVZ.ToString()}", IsIndeterminate = true
                };

                //Dispatcher.Invoke(() =>
                //{

                if (addToListBoxTask)
                {
                    Dispatcher.Invoke(() =>
                    {
                        Bindings.listBoxTaskItemsSource.Add(curItemLBT);
                    });
                }
                try
                {
                    this.Log(string.Format($"Выполнение {command} на {selectedIP.NBNameOrIP()}..."), false, false, string.Empty, true);
                    string nbNameOrIP = selectedIP.NBNameOrIP();
                    string ipaddress  = selectedIP.IPAddress;


                    using (SshClient client = new SshClient(ipaddress, login, password))
                    {
                        client.Connect();
                        StringBuilder commandBuild = new StringBuilder();
                        commandBuild.AppendLine(@"#!/bin/bash");
                        commandBuild.AppendLine($"TempPass={password}");
                        commandBuild.AppendLine(commandinresult);
                        string commandExec    = commandBuild.ToString().Replace("\r\n", "\n");
                        bool uploadFileStoped = false;

                        var runCommand = client.CreateCommand(commandExec);
                        var runClient  = runCommand.BeginExecute((x) =>
                        {
                            var temp = curItemLBT.StopProcess;
                            if (curItemLBT.StopProcess)
                            {
                                if (!uploadFileStoped)
                                {
                                    try
                                    {
                                        uploadFileStoped = true;
                                        showWindow       = false;
                                        client.Disconnect();
                                        //return $"Прервано выполнение {command}";
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }
                        });

                        string result = runCommand.EndExecute(runClient);

                        client.Disconnect();
                        if (showWindow)
                        {
                            base.Dispatcher.BeginInvoke((Action)(() =>
                            {
                                SSHReportWindow window = new SSHReportWindow(this)
                                {
                                    Owner = this,
                                    Title = string.Format($"Команда SSH {command} на {nbNameOrIP}"),
                                    Text = { Text = result },
                                    SSHStatusBarText = { Text = string.Format($"Команда SSH {command} на {nbNameOrIP} выполнена.") }
                                };
                                this.Log(window.SSHStatusBarText.Text, false, false, "", false);
                                window.Show();
                            }));
                        }
                    }
                }
                catch (ArgumentException exception)
                {
                    Log("Необходимо выбрать логин и пароль", true, true, exception.StackTrace, false);
                }
                catch (Exception exception)
                {
                    this.Log(exception.Message, true, true, exception.StackTrace, false);
                }

                //});
            }));

            runThread.Start();


            //while (!curItemLBT.StopProcess || (runThread.ThreadState != System.Threading.ThreadState.Stopped) || (runThread.ThreadState != System.Threading.ThreadState.Aborted))
            //{

            //    if (!(runThread.ThreadState == System.Threading.ThreadState.Stopped))
            //    {
            //        runThread.Abort();
            //    }
            //}
        }
Пример #2
0
        /// <summary>
        /// Метод копирования файла на хост
        /// </summary>
        /// <param name="fileName">имя файла</param>
        /// <param name="pathToFile">путь к файлу</param>
        /// <param name="pathDestination">путь, куда будет скопирован файл</param>
        /// <param name="ipAddress">ip адрес хоста</param>
        /// <param name="login">логин, для подключения к хосту</param>
        /// <param name="password">пароль, для подключения к хосту</param>
        public void SftpCopy(string fileName, string pathToFile, string pathDestination, string ipAddress, string login, string password, bool addToListBoxTask = true)
        {
            try
            {
                bool endRunThread = false;
                var  startThread  = new Thread(new ThreadStart(() =>
                {
                    //BackgroundWorker progressBarCopyWorker = new BackgroundWorker();
                    PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ipAddress, 22, login, password);
                    connectionInfo.Timeout         = TimeSpan.FromSeconds(15);
                    string fileFullName            = System.IO.Path.Combine(pathToFile, fileName);
                    string fileDestinationFullName = System.IO.Path.Combine(pathDestination, fileName);

                    ItemListBoxTask curItemLBT = new ItemListBoxTask()
                    {
                        IPOrName = ipAddress, Description = $"Выполняется копирование: {fileName} в {pathDestination}", CVZNumber = $"ЦВЗ№{SelectedTT.NumberCVZ.ToString()}"
                    };


                    #region Скопировать файл на хост
                    // Проверка доступности файла
                    if (File.Exists(fileFullName))
                    {
                        //Dispatcher.Invoke(() =>
                        //{

                        if (addToListBoxTask)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                Bindings.listBoxTaskItemsSource.Add(curItemLBT);
                            });
                            //ListBoxTask.Items.Add(curItemLBT);
                        }
                        using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read))
                        {
                            curItemLBT.MaxValueProgressBar = stream.Length;
                            //progressBarStatus.Maximum = stream.Length;
                        }
                        //progressBarStatus.Value = 0;
                        //progressBarStatus.Visibility = Visibility.Visible;
                        //Bindings.StatusBarText = $"Выполняется копирование файла {fileName}";
                        bool uploadFileStoped = false;
                        UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBarStatus.SetValue);
                        //UpdateProgressBarDelegate updProgressItemTask = new UpdateProgressBarDelegate(progressBarStatus.SetValue);
                        using (var sftp = new SftpClient(connectionInfo))
                        {
                            try
                            {
                                sftp.Connect();

                                using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read))
                                {
                                    var startUpload = sftp.BeginUploadFile(stream, fileDestinationFullName, (asyncCallback) =>
                                    {
                                        //sftp.EndUploadFile(startUpload);
                                        endRunThread = true;
                                    }, null, (progressBarStatusCallBack) =>
                                    {
                                        var temp = curItemLBT.StopProcess;
                                        if (curItemLBT.StopProcess)
                                        {
                                            if (!uploadFileStoped)
                                            {
                                                try
                                                {
                                                    uploadFileStoped = true;
                                                    sftp.Disconnect();
                                                    endRunThread = true;
                                                }
                                                catch (Exception)
                                                {
                                                }
                                            }
                                        }
                                        Dispatcher.Invoke((Action)(() => { curItemLBT.CurValueProgressBar = (double)progressBarStatusCallBack; }));
                                        Dispatcher.Invoke(updProgress, System.Windows.Threading.DispatcherPriority.Render, new object[] { MetroProgressBar.ValueProperty, (double)progressBarStatusCallBack });
                                    });


                                    while (!startUpload.IsCompleted)
                                    {
                                        if (startUpload.IsCompleted)
                                        {
                                            stream.Close();
                                            stream.Dispose();
                                            endRunThread = true;
                                        }
                                    }

                                    Log(!uploadFileStoped ? $"Выполнено копирование {fileDestinationFullName} на хост {ipAddress}" : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true);
                                }
                            }
                            //catch(excep)
                            catch (Exception ex)
                            {
                                Log(!uploadFileStoped ? ex.Message : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true);
                                //Log(ex.Message, true, false, ex.StackTrace);
                            }
                            finally
                            {
                                try
                                {
                                    sftp.Disconnect();
                                    sftp.Dispose();
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                    }
                    else
                    {
                        Log($"{fileFullName} не доступен", true, true);
                    }

                    #endregion
                    //}
                }));
                startThread.Start();

                //startThread.Suspend();

                //new Thread(new ThreadStart(() =>
                //{
                //    while (!endRunThread)
                //    {
                //        if (endRunThread)
                //        {
                //            int endD = 1;
                //        }
                //    }
                //})).Start();
            }
            catch (Exception ex)
            {
                Log(ex.Message, true, true, ex.StackTrace);
            }
        }