示例#1
0
        public override void ExecuteCommand(String commandString, String commandArguments, String terminateCommand, String terminateCommandParameters)
        {
            if (command != null)
            {
                command.Dispose();
            }

            command     = client.CreateCommand(commandString);
            asyncResult = command.BeginExecute();

            //return command;
        }
示例#2
0
 protected void Cleanup()
 {
     lock (this)
     {
         _sshCommand?.Dispose();
     }
 }
示例#3
0
 private void Dispose()
 {
     Command.Dispose();
     FoundConsoleEnd = null;
     Writer?.Close(); Writer?.Dispose(); Writer = StreamWriter.Null;
     Terminal?.Close(); Terminal?.Dispose();
     Terminal = null;
 }
示例#4
0
 public Task Execute(SshClient ssh)
 {
     cmd?.Dispose();
     cmd = ssh.CreateCommand(text);
     return(Task.Factory.FromAsync((callback, state) => cmd.BeginExecute(callback, state), res => {
         cmd.EndExecute(res);
         OnCompleted();
     }, null));
 }
示例#5
0
        public void DisposeTest()
        {
            Session    session     = null;                                 // TODO: Initialize to an appropriate value
            string     commandText = string.Empty;                         // TODO: Initialize to an appropriate value
            SshCommand target      = new SshCommand(session, commandText); // TODO: Initialize to an appropriate value

            target.Dispose();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
示例#6
0
        public static void CopyCommand()
        {
            if (sshClient == null && sshClient.IsConnected)
            {
                MessageBox.Show("没有打开链接!!!");
                return;
            }
            //普通执行,这个无法正常执行cd指令
            SshCommand cmd = sshClient.CreateCommand("ls ");
            string     res = cmd.Execute();

            Console.Write(res);
            cmd.Dispose();
        }
示例#7
0
        /// <summary>
        /// 해당 Client에서 입력된 명령을 실행.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="cmd"></param>
        public static (string msg, bool isSuccessful) ExcuteCommand(SshClient client, string cmd)
        {
            SshCommand sshCmd     = null;
            bool       successful = true;

            StringBuilder result = new StringBuilder();
            {
                try
                {
                    sshCmd = client.CreateCommand(cmd);
                    var t = sshCmd.Execute();

                    if (string.IsNullOrEmpty(sshCmd.Error))
                    {
                        result.Append(sshCmd.Result);
                    }
                    else
                    {
                        result.Append(sshCmd.Result);
                        result.Append(sshCmd.Error);
                        successful = false;
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine($"SshHelper.ExcuteCommand(): {e.Message}");
                    result.Append(e.Message);

                    if (result.ToString() == "CommandText property is empty.")
                    {
                        result.Append("\n");
                    }

                    successful = false;
                }

                sshCmd?.Dispose();

                return(msg : result.ToString(), isSuccessful : successful);
            }
        }
示例#8
0
        public void Start(int timeout)
        {
            if (!client.IsConnected)
            {
                throw new Exception("Could not contact TayzGrid services on target machine.");
            }

            Status = GetServiceStatus(client);

            if (Status == ServiceStatus.Running)
            {
                return;
            }

            if (Status == ServiceStatus.DoesNotExist)
            {
                throw new Exception("Either TayzGrid services does not exist on target machine or permission denied to start service. Contact your administrator to control this behavior.");
            }

            AsyncCallback callback = new AsyncCallback(ICommandResult);
            SshCommand    command  = client.CreateCommand("");

            ExecuteAsyncCommand(client, ServiceCommands.START, callback, command);
            System.Threading.Thread.Sleep(timeout * 1000);

            int retry = 0;

            while (retry < 2)
            {
                Status = GetServiceStatus(client);
                if (Status == ServiceStatus.Running)
                {
                    return;
                }

                retry++;
                Thread.Sleep(timeout * 1000);
            }
            command.Dispose();
            throw new Exception("Unable to start service in the given timeout period.");
        }
示例#9
0
        public void Stop(int timeout)
        {
            if (!client.IsConnected)
            {
                throw new Exception("Could not contact TayzGrid services on target machine.");
            }

            Status = GetServiceStatus(client);

            if (Status == ServiceStatus.Stopped)
            {
                return;
            }

            if (Status == ServiceStatus.DoesNotExist)
            {
                throw new Exception("Could not contact TayzGrid services on target machine");
            }

            AsyncCallback callback = new AsyncCallback(ICommandResult);
            SshCommand    command  = client.CreateCommand("");

            ExecuteAsyncCommand(client, ServiceCommands.STOP, callback, command);
            System.Threading.Thread.Sleep(timeout * 500);

            int retry = 0;

            while (retry < 2)
            {
                Status = GetServiceStatus(client);
                if (Status == ServiceStatus.Stopped)
                {
                    return;
                }

                retry++;
                Thread.Sleep(timeout * 500);
            }
            command.Dispose();
            throw new Exception("Unable to stop services in the given timeout period.");
        }
示例#10
0
 /// <summary>
 /// Close the robot output stream
 /// </summary>
 /// <returns>True if successful</returns>
 public static Task <bool> CloseRobotOutputStream()
 {
     return(Task.Run(() =>
     {
         if (outputStreamCommand != null && !openingOutputStream && !closingOutputStream)
         {
             try
             {
                 closingOutputStream = true;
                 outputStreamCommand.CancelAsync();
                 outputStreamCommand.Dispose();
                 outputStreamCommand = null;
                 closingOutputStream = false;
             }
             catch (Exception e)
             {
                 Debug.Log(e.ToString());
                 closingOutputStream = false;
                 return false;
             }
         }
         return true;
     }));
 }
示例#11
0
        public async Task <Data.ObjectResult> CloneProduct(string fromLocation, string toDestination, string dbName, string mysqlUsername, string mysqlPassword, string scriptLocation)
        {
            using (var client = new SshClient("103.7.41.51", "root", "Gsoft@235"))
            {
                try
                {
                    client.Connect();



                    if (client.IsConnected)
                    {
                        ////Copy source tu folder goc fromLocation sang folder moi toDestination
                        //client.RunCommand($"mkdir '{toDestination}'");
                        client.RunCommand($"mkdir '{toDestination}' && cd '{fromLocation}' && cp * '{toDestination}'");
                        /*------------*/
                        //Tao Mysql User va DB, gan user quan ly DB vua tao
                        var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306);
                        client.AddForwardedPort(portForwarded);
                        portForwarded.Start();
                        DatabaseConnect mySqlConnector = new DatabaseConnect("Server=127.0.0.1; Port=3306; Uid=root; Pwd=JOpaqGH7N7xz;");
                        //string createUserandDBScript = $"CREATE DATABASE IF NOT EXISTS {dbName}; CREATE USER '{mysqlUsername}'@'localhost' IDENTIFIED BY '{mysqlPassword}'; GRANT ALL PRIVILEGES ON  {dbName}. * TO '{mysqlUsername}'@'localhost';FLUSH PRIVILEGES;";

                        string createDatabaseScript = $"CREATE DATABASE IF NOT EXISTS {dbName};";
                        string createUserScript     = $"CREATE USER '{mysqlUsername}'@'localhost' IDENTIFIED BY '{mysqlPassword}';";
                        string grantPermission      = $"GRANT ALL PRIVILEGES ON  {dbName}. * TO '{mysqlUsername}'@'localhost';";
                        string resetPermissionTable = $"FLUSH PRIVILEGES;";

                        Data.ObjectResult result = new Data.ObjectResult();
                        //khoi tao ket noi MySQL
                        result = mySqlConnector.OpenConnection();
                        if (result.isSucceeded == false)
                        {
                            return(result);
                        }

                        result = await mySqlConnector.ExecuteCommand(createDatabaseScript);

                        if (result.isSucceeded == false)
                        {
                            //  result.ErrorMessage = "Lỗi xảy ra khi tạo DB ";
                            return(result);
                        }
                        result = await mySqlConnector.ExecuteCommand(createUserScript);

                        if (result.isSucceeded == false)
                        {
                            // result.ErrorMessage= "Không thể tạo User Mysql";
                            return(result);
                        }
                        result = await mySqlConnector.ExecuteCommand(grantPermission);

                        if (result.isSucceeded == false)
                        {
                            // result.ErrorMessage = $"Không thể gán quyền user {mysqlUsername} cho Database {dbName}";
                            return(result);
                        }
                        result = await mySqlConnector.ExecuteCommand(resetPermissionTable);

                        if (result.isSucceeded == false)
                        {
                            return(result);
                        }
                        result = await mySqlConnector.ExecuteCommand($"USE {dbName};");

                        if (result.isSucceeded == false)
                        {
                            return(result);
                        }


                        //execute file script vao DB vua tao
                        SshCommand getScriptFileCommand = client.CreateCommand($"cat '{scriptLocation}'");

                        string scriptContent = getScriptFileCommand.Execute();
                        if (!String.IsNullOrEmpty(scriptContent))
                        {
                            result = await mySqlConnector.ExecuteCommand(scriptContent);

                            if (result.isSucceeded == false)
                            {
                                return(result);
                            }
                        }


                        //Tao Subdomain
                        string useCWP = "USE root_cwp;";
                        result = await mySqlConnector.ExecuteCommand(useCWP);

                        if (result.isSucceeded == false)
                        {
                            return(result);
                        }

                        string insertSubdomain = $"Insert into subdomains (subdomain,domain,user,path,setup_time) values('subdomain','gwebsite.net','gwebsite','home/gwebsite/public_html/subdomain','{DateTime.Now}')";
                        result = await mySqlConnector.ExecuteCommand(insertSubdomain);

                        if (result.isSucceeded == false)
                        {
                            return(result);
                        }

                        mySqlConnector.CloseConnection();
                        getScriptFileCommand.Dispose();
                        //hieu chinh file wp-config
                        string     configFileLocation     = toDestination + "/wp-config.php";
                        SshCommand getWordpressConfigFile = client.CreateCommand($"cat '{configFileLocation}'");
                        string     wpconfigContent        = getWordpressConfigFile.Execute();
                        if (!String.IsNullOrEmpty(wpconfigContent))
                        {
                            wpconfigContent = wpconfigContent.Replace("define('DB_NAME','');", $"define('DB_NAME','{dbName}');");
                            wpconfigContent = wpconfigContent.Replace("define('DB_USER','');", $"define('DB_USER','{mysqlUsername}');");
                            wpconfigContent = wpconfigContent.Replace("define('DB_PASSWORD','');", $"define('DB_PASSWORD','{mysqlPassword}');");
                            getWordpressConfigFile.Dispose();
                            using (SftpClient sftpClient = new SftpClient("103.7.41.51", 22, "root", "Gsoft@235"))
                            {
                                sftpClient.Connect();
                                if (sftpClient.IsConnected)
                                {
                                    try
                                    {
                                        using (MemoryStream memStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(wpconfigContent)))
                                        {
                                            try
                                            {
                                                sftpClient.UploadFile(memStream, configFileLocation, true);
                                            }
                                            catch (Exception ex)
                                            {
                                                Data.ObjectResult rs = new Data.ObjectResult();
                                                rs.isSucceeded  = false;
                                                rs.ErrorMessage = "Có lỗi xảy ra khi cập nhật lại file wp-config - " + ex.Message;
                                                return(rs);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Data.ObjectResult rs = new Data.ObjectResult();
                                        rs.isSucceeded  = false;
                                        rs.ErrorMessage = "Có lỗi xảy ra khi tạo file wp-config - " + ex.Message;
                                        return(rs);
                                    }
                                }
                            }
                        }



                        client.Disconnect();
                    }
                    else
                    {
                        Data.ObjectResult objrs = new Data.ObjectResult();
                        objrs.isSucceeded  = false;
                        objrs.ErrorMessage = "Kết nối SSH đến VPS thất bại";
                        return(objrs);
                    }
                    Data.ObjectResult objResult = new Data.ObjectResult();
                    objResult.isSucceeded  = true;
                    objResult.ErrorMessage = "Clone source thành công";

                    return(objResult);
                }
                catch (Exception ex)
                {
                    Data.ObjectResult objrs = new Data.ObjectResult();
                    objrs.isSucceeded  = false;
                    objrs.ErrorMessage = "Lỗi - " + ex.Message;
                    return(objrs);
                }
                finally
                {
                    client.Disconnect();
                }
            }
        }
 private void Act()
 {
     _sshCommand.Dispose();
 }
示例#13
0
 public void Abort()
 {
     SshRequest?.Dispose();
 }
示例#14
0
 [Ignore] // placeholder for actual test
 public void DisposeTest()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     var encoding = Encoding.UTF8;
     SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
     target.Dispose();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
示例#15
0
        public override bool Execute(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, Dictionary <string, string> env = null,
                                     Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);

            if (!this.IsConnected)
            {
                throw new InvalidOperationException("The SSH session is not connected.");
            }
            process_status = ProcessExecuteStatus.Unknown;
            process_output = "";
            process_error  = "";
            if (env != null && env.Count > 0)
            {
                StringBuilder vars = new StringBuilder();
                foreach (KeyValuePair <string, string> kv in env)
                {
                    vars.AppendFormat("{0}={1} ", kv.Key, kv.Value);
                }
                command = vars.ToString() + command;
            }
            SshCommand cmd = this.SshClient.CreateCommand(command + " " + arguments);

            Debug("Executing command {0} {1}.", command, arguments);
            Stopwatch cs = new Stopwatch();

            cs.Start();
            CommandAsyncResult result;

            try
            {
                result = cmd.BeginExecute(new AsyncCallback(SshCommandAsyncCallback), new KeyValuePair <SshCommand, Stopwatch>(cmd, cs)) as CommandAsyncResult;
                cmd.EndExecute(result);
            }
            catch (SshConnectionException sce)
            {
                Error(caller, sce, "SSH connection error attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (SshOperationTimeoutException te)
            {
                Error(caller, te, "SSH connection timeout attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (SshException se)
            {
                Error(caller, se, "SSH error attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (Exception e)
            {
                Error(caller, e, "Error attempting to execute over SSH {0} {1}.", command, arguments);
                return(false);
            }
            KeyValuePair <SshCommand, Stopwatch> s = (KeyValuePair <SshCommand, Stopwatch>)result.AsyncState;

            process_output = s.Key.Result.Trim();
            process_error  = s.Key.Error.Trim();
            if (s.Value.IsRunning)
            {
                s.Value.Stop();
            }
            process_output = cmd.Result.Trim();
            process_error  = process_output + cmd.Error.Trim();
            if (cmd.ExitStatus == 0)
            {
                Debug(caller, "Execute {0} returned zero exit code. Output: {1}.", command + " " + arguments, process_output);
                process_status = ProcessExecuteStatus.Completed;
                cmd.Dispose();
                return(true);
            }
            else
            {
                process_status = ProcessExecuteStatus.Error;
                Debug(caller, "Execute {0} returned non-zero exit code {2}. Error: {1}.", command + " " + arguments, process_error, cmd.ExitStatus);
                cmd.Dispose();
                return(false);
            }
        }
示例#16
0
        /// <summary>
        /// Perform some kind of control action
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            bool success = false;
            var  rxData  = new StringBuilder();

            SshCommand cmd = null;

            try
            {
                if (string.IsNullOrEmpty(ErrorResponse) && string.IsNullOrEmpty(SuccessResponse))
                {
                    throw new Exception("Need Error/Success response defined for StreamCommand");
                }

                Logger.Debug("Command Tx: " + Send);

                cmd = client.CreateCommand(Send);
                cmd.CommandTimeout = new TimeSpan(0, 0, TimeoutSecs);
                cmd.BeginExecute(new AsyncCallback(ExecutionCallback), cmd);

                var reader = new StreamReader(cmd.OutputStream);

                DateTime dtStart = DateTime.Now;
                long     intervalS;
                bool     timedOut = false;
                do
                {
                    if (reader.BaseStream.Length > 0)
                    {
                        rxData.Append(reader.ReadToEnd());
                    }

                    if (rxData.Length > 0)
                    {
                        if (!string.IsNullOrEmpty(ErrorResponse))
                        {
                            if (rxData.ToString().Contains(ErrorResponse))
                            {
                                Logger.Warn("- Error response: " + rxData);
                                return(false);
                            }
                        }

                        if (!string.IsNullOrEmpty(SuccessResponse))
                        {
                            if (rxData.ToString().Contains(SuccessResponse))
                            {
                                Logger.Warn("- Success response: " + rxData);
                                success = true;
                            }
                        }
                    }

                    intervalS = (long)DateTime.Now.Subtract(dtStart).TotalSeconds;
                    if (TimeoutSecs > 0)
                    {
                        timedOut = intervalS > TimeoutSecs;
                    }
                } while (!timedOut && !success);

                if (timedOut)
                {
                    UpdateUI("*** Timed out");
                    return(false);
                }

                // Perform regexp replacement...
                Output = !string.IsNullOrEmpty(OutputRegExp) ? Regex.Match(rxData.ToString(), OutputRegExp).Value : rxData.ToString();

                Logger.Debug("Output: " + (!string.IsNullOrEmpty(Output) ? Output : "<none>"));
            }
            catch (Exception ex)
            {
                Logger.Warn("Exception in worker thread: " + ex.Message);
                success = false;
            }
            finally
            {
                try
                {
                    // TODO: We seem to timeout and disconnect if we try to cancel. Perhaps better for now to kill the process in the next command instead
                    //cmd.CancelAsync();
                    cmd.Dispose();
                    cmd = null;
                }
                catch (Exception e)
                {
                    Logger.Warn("Exception stopping shell: " + e.Message);
                }
            }
            return(success);
        }
示例#17
0
 public void CleanUp()
 {
     _client.Disconnect();
     _client.Dispose();
     _command.Dispose();
 }