private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionAMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _channelSessionBMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;
            _asyncResultA = null;
            _asyncResultB = null;

            var seq = new MockSequence();
            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionAMock.Object);
            _channelSessionAMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionAMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
                .Returns(true)
                .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionAMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResultA = _sshCommand.BeginExecute();
            _sshCommand.EndExecute(_asyncResultA);

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionBMock.Object);
            _channelSessionBMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionBMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);
        }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock         = new Mock <ISession>(MockBehavior.Strict);
            _channelSessionAMock = new Mock <IChannelSession>(MockBehavior.Strict);
            _channelSessionBMock = new Mock <IChannelSession>(MockBehavior.Strict);
            _commandText         = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding            = Encoding.UTF8;
            _asyncResultA        = null;
            _asyncResultB        = null;

            var seq = new MockSequence();

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionAMock.Object);
            _channelSessionAMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionAMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
            .Returns(true)
            .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionAMock.InSequence(seq).Setup(p => p.IsOpen).Returns(true);
            _channelSessionAMock.InSequence(seq).Setup(p => p.Close());
            _channelSessionAMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand   = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResultA = _sshCommand.BeginExecute();
            _sshCommand.EndExecute(_asyncResultA);

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionBMock.Object);
            _channelSessionBMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionBMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);
        }
Example #3
0
        public IAsyncResult BeginTaskExecute(TaskInfo ti, out SshCommand cmd)
        {
            cmd = sClient.CreateCommand(ti.ExecString);
            IAsyncResult syncObj = cmd.BeginExecute();

            return(syncObj);
        }
        public static Task <string> RunCommandAsync(this SshClient client, string command)
        {
            SshCommand cmd = client.CreateCommand(command);

            return(Task <String> .Factory.FromAsync((callback, state) => cmd.BeginExecute(callback, state),
                                                    cmd.EndExecute, null));
        }
Example #5
0
        public void Init(SSHParam inparam, STRule inrule, string innodename)
        {
            sshParam = inparam;
            string filepathname = string.Format("/tmp/{0}{1}{2}", innodename, DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"), inrule.rFileName);

            inrule.rFileName = filepathname;
            STTask task = new STTask();

            task.myRule = inrule;
            task.hName  = innodename;
            task.GetCmdLine();
            myTask = task;
            try {
                sshclient = new SshClient(sshParam.hostIP, sshParam.userName, sshParam.userPWD);
                if (sshclient == null)
                {
                    return;
                }
                sshclient.Connect();
                sshcmd     = sshclient.CreateCommand(task.GetCmdLine());
                ssharesult = sshcmd.BeginExecute();
            } catch (Exception exc) {
                exc.ToString();
            }
        }
Example #6
0
 /// <summary>
 /// Open the robot output stream
 /// </summary>
 /// <returns>A stream reader to read from the robot output stream</returns>
 public static StreamReader CreateRobotOutputStream()
 {
     if (outputStreamCommand == null && !openingOutputStream && !closingOutputStream)
     {
         try
         {
             openingOutputStream = true;
             ClientManager.Connect();
             if (ClientManager.Instance.RunCommand(CHECK_LOG_EXISTS_COMMAND).ExitStatus == 0)
             {
                 outputStreamCommand = ClientManager.Instance.CreateCommand(RECEIVE_PRINTS_COMMAND);
                 outputStreamCommand.CommandTimeout = TimeSpan.FromSeconds(SSH_COMMAND_TIMEOUT);
                 outputStreamCommandResult          = outputStreamCommand.BeginExecute();
                 openingOutputStream = false;
             }
             else
             {
                 throw new Exception("Remote user program log file not found");
             }
         }
         catch (Exception e)
         {
             Debug.Log(e.ToString());
             outputStreamCommand = null;
             openingOutputStream = false;
             return(null);
         }
     }
     return(new StreamReader(outputStreamCommand.OutputStream));
 }
Example #7
0
        public bool RunSheell(string command)
        {
            SshCommand cmd    = _sshClient.CreateCommand(command);
            var        result = cmd.BeginExecute();

            _logger(command, LogLevel.Info);
            using (var reader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true))
            {
                while (!result.IsCompleted || !reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (!string.IsNullOrEmpty(line))
                    {
                        _logger(line, LogLevel.Info);
                    }
                }
            }

            cmd.EndExecute(result);

            if (!string.IsNullOrEmpty(cmd.Error))
            {
                if (cmd.Error.Contains("unable to resolve host"))
                {
                    _logger(cmd.Error, LogLevel.Warn);
                    return(true);
                }
                _logger(cmd.Error, LogLevel.Error);
                return(false);
            }

            return(true);
        }
        public void EndExecute_ChannelClosed_ShouldDisposeChannelSession()
        {
            var seq = new MockSequence();

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
            .Returns(true)
            .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());

            var asyncResult = _sshCommand.BeginExecute();

            _sshCommand.EndExecute(asyncResult);

            _channelSessionMock.Verify(p => p.Dispose(), Times.Once);
        }
Example #9
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));
 }
        public static Task <string> RunCommandAsync(this SshClient client, string command, int timeout)
        {
            SshCommand cmd = client.CreateCommand(command);

            cmd.CommandTimeout = TimeSpan.FromMilliseconds(timeout);

            return(Task <String> .Factory.FromAsync((callback, state) => cmd.BeginExecute(callback, state),
                                                    cmd.EndExecute, null));
        }
Example #11
0
 public static Task <string> ExecuteAsync(this SshCommand command,
                                          TaskFactory <string> factory        = null,
                                          TaskCreationOptions creationOptions = default(TaskCreationOptions),
                                          TaskScheduler scheduler             = null)
 {
     return((factory = factory ?? Task <string> .Factory).FromAsync(
                command.BeginExecute(),
                command.EndExecute,
                creationOptions, scheduler ?? factory.Scheduler ?? TaskScheduler.Current));
 }
Example #12
0
 public SshStarterCommand(SshCommand sshCommand)
 {
     _sshCommand  = sshCommand;
     _asyncResult = _sshCommand.BeginExecute(ar =>
     {
         ExitCode = sshCommand.ExitStatus;
         Error    = sshCommand.Error;
         OnExit?.Invoke(this, EventArgs.Empty);
     });
 }
Example #13
0
        // TailRun. The tailing thread. runs a 'tail' command on the host and processes lines read
        public void TailRun()
        {
            StreamReader streamReader = null;

            tailing = true;

            // replace FILE marker in command with the actual file name
            string cmd = tailCmd.Replace("FILE", fileName);

            try
            {
                while (tailing && running)
                {
                    // create the tail command & start it. run it asynchronusly so we can read
                    // anc check for stop flags
                    SshCommand sshCommand = ssh.CreateCommand(cmd);
                    asynch       = sshCommand.BeginExecute();
                    streamReader = new StreamReader(sshCommand.OutputStream);

                    // read anything that is returned and add to lines queue
                    while (!asynch.IsCompleted && running && tailing)
                    {
                        bool   reading = false;
                        string line    = streamReader.ReadLine();
                        if (line != null)
                        {
                            reading = true;
                            EnqueueLine(line, false);
                        }
                        else
                        {
                            // if nothing read, just wait a bit befor
                            System.Threading.Thread.Sleep(100);
                        }
                        state = lineCount.ToString() + " lines" + (reading ? " (reading)" : " (waiting)");
                    }
                }
            }
            catch (Exception e)
            {
                running = false;
                EnqueueLine(e.Message + ": Can't connect to " + host, true);
                throw e;
            }

            try
            {
                streamReader.Close();
            }
            catch (Exception e)
            {
                running = false;
                EnqueueLine(e.Message + ": Can't connect to " + host, true);
            }
        }
 private void _executeCommand(string commandType, SshCommand command)
 {
     if (commandType == "video_streaming")
     {
         var asyncExecute = command.BeginExecute();
         command.EndExecute(asyncExecute);
     }
     else
     {
         command.Execute();
     }
 }
Example #15
0
 private void Act()
 {
     try
     {
         _sshCommand.BeginExecute();
         Assert.Fail();
     }
     catch (InvalidOperationException ex)
     {
         _actualException = ex;
     }
 }
Example #16
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;
        }
        public List <Tuple <string, ProcessExecuteStatus, string, string> > ExecuteMany(List <Tuple <string, string> > commands)
        {
            CallerInformation caller = this.Here();

            if (!this.IsConnected)
            {
                throw new InvalidOperationException("The SSH session is not connected.");
            }
            List <Tuple <string, ProcessExecuteStatus, string, string> > results = new List <Tuple <string, ProcessExecuteStatus, string, string> >(commands.Count);
            object    results_lock = new object();
            Stopwatch sw           = new Stopwatch();

            sw.Start();
            Parallel.ForEach(commands, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 20
            }, (_c, state) =>
            {
                string process_output = string.Empty;
                string process_error  = string.Empty;
                SshCommand cmd        = this.SshClient.CreateCommand(_c.Item1 + " " + _c.Item2);
                Stopwatch cs          = new Stopwatch();
                cs.Start();
                CommandAsyncResult result = cmd.BeginExecute(new AsyncCallback(SshCommandAsyncCallback), new KeyValuePair <SshCommand, Stopwatch>(cmd, cs)) as CommandAsyncResult;
                cmd.EndExecute(result);
                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();
                }
                if (process_output != string.Empty)
                {
                    lock (results_lock)
                    {
                        results.Add(new Tuple <string, ProcessExecuteStatus, string, string>(_c.Item1, ProcessExecuteStatus.Completed, process_output, process_error));
                    }
                    Debug(caller, "Execute {0} completed with {1} {2}.", s.Key.Result.Length, cmd.CommandText, process_output, process_error);
                }
                else
                {
                    lock (results_lock)
                    {
                        results.Add(new Tuple <string, ProcessExecuteStatus, string, string>(_c.Item1, ProcessExecuteStatus.Error, process_output, process_error));
                    }
                    Debug(caller, "Execute {0} did not complete successfully: {1} {2}.", s.Key.Result.Length, cmd.CommandText, process_output, process_error);
                }
            });
            return(results);
        }
Example #18
0
 public void BeginExecuteTest1()
 {
     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
     string commandText1 = string.Empty; // TODO: Initialize to an appropriate value
     AsyncCallback callback = null; // TODO: Initialize to an appropriate value
     object state = null; // TODO: Initialize to an appropriate value
     IAsyncResult expected = null; // TODO: Initialize to an appropriate value
     IAsyncResult actual;
     actual = target.BeginExecute(commandText1, callback, state);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Example #19
0
        protected string ExecuteCommandAsync(SshClient sshClient, string command)
        {
            string tmp;

            using (SshCommand cmd = sshClient.CreateCommand(command))
            {
                cmd.BeginExecute();
                using (StreamReader reader = new StreamReader(cmd.OutputStream))
                {
                    tmp = reader.ReadToEnd();
                }
            }
            return(tmp);
        }
Example #20
0
        public void BeginExecuteTest1()
        {
            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
            string        commandText1 = string.Empty;                         // TODO: Initialize to an appropriate value
            AsyncCallback callback     = null;                                 // TODO: Initialize to an appropriate value
            object        state        = null;                                 // TODO: Initialize to an appropriate value
            IAsyncResult  expected     = null;                                 // TODO: Initialize to an appropriate value
            IAsyncResult  actual;

            actual = target.BeginExecute(commandText1, callback, state);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Example #21
0
        public void fixAppStore()
        {
            SshClient sshclient = new SshClient(host, user, pass);

            try
            {
                txtlog.Text += "Ejecutando comandos \r\n";
                sshclient.Connect();
                SshCommand appstore = sshclient.CreateCommand(@"mv /var/mobile/Library/Preferences/com.apple.purplebuddy.plist /var/mobile/Library/Preferences/com.apple.purplebuddy.plist.old");

                var asynch = appstore.BeginExecute();
                while (!asynch.IsCompleted)
                {
                    //  Waiting for command to complete...
                    Thread.Sleep(2000);
                }
                var result = appstore.EndExecute(asynch);
                sshclient.Disconnect();
            }
            catch (Exception e)
            {
                Analytics.TrackEvent(e.Message + " : " + uid);
                if (e.Message.Contains("SSH protocol identification"))
                {
                    MessageBox.Show("Verifique el etado de su JailBreak", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            ScpClient scpClient = new ScpClient(host, user, pass);

            try
            {
                scpClient.Connect();
                scpClient.Upload(new FileInfo(path + "\\library\\com.apple.purplebuddy.plist"), "/var/mobile/Library/Preferences/com.apple.purplebuddy.plist");
                scpClient.Disconnect();
            }
            catch (Exception e)
            {
                Analytics.TrackEvent(e.Message + " : " + uid);
                if (e.Message.Contains("SSH protocol identification"))
                {
                    MessageBox.Show("Verifique el estado de su JailBreak", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Process.Start("https://youtu.be/DlUuJt2Xhuw");
                }
            }
            txtlog.Text += "AppStore parcheado, Reinicie su dispositivo \r\n";
            stopProxi();
        }
Example #22
0
 public sessionObj(string inHost, string inUserName, string inPwd, string inCmd)
 {
     try {
         sshclient = new SshClient(inHost, inUserName, inPwd);
         if (sshclient == null)
         {
             return;
         }
         sshclient.Connect();
         sshcmdline = inCmd;
         sshcmd     = sshclient.CreateCommand(sshcmdline);
         var result = sshcmd.BeginExecute();
     } catch (Exception exc) {
         exc.ToString();
     }
 }
Example #23
0
        // Execute a shell command
        public CmdResponse ExecShell(string shellString)
        {
            SshCommand   cmd  = SshClient.CreateCommand(shellString);
            IAsyncResult task = cmd.BeginExecute();

            Console.WriteLine(shellString);

            while (!task.IsCompleted)
            {
                Thread.Sleep(500);
            }
            CmdResponse response = new CmdResponse(shellString, cmd.ExitStatus, cmd.Error, cmd.Result);

            cmd.EndExecute(task);

            return(response);
        }
        public static async Task ExecuteAsync(this SshCommand sshCommand, IProgress <ScriptOutputLine> progress, CancellationToken cancellationToken)
        {
            var asyncResult        = sshCommand.BeginExecute();
            var stdoutStreamReader = new StreamReader(sshCommand.OutputStream);
            var stderrStreamReader = new StreamReader(sshCommand.ExtendedOutputStream);

            while (!asyncResult.IsCompleted)
            {
                await CheckOutputAndReportProgress(sshCommand, stdoutStreamReader, stderrStreamReader, progress, cancellationToken);

                await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
            }

            sshCommand.EndExecute(asyncResult);

            await CheckOutputAndReportProgress(sshCommand, stdoutStreamReader, stderrStreamReader, progress, cancellationToken);
        }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;

            var seq = new MockSequence();
            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _sshCommand.BeginExecute();
        }
Example #26
0
        /// <summary>
        /// Runs command and prints output to window if talking to Debian Linux
        /// </summary>
        /// <param name="command"></param>
        private bool DoLinuxCommand(string command, SshClient linuxClient)
        {
            if (xmlConfig.PingTestMode)
            {
                command = $"ping {xmlConfig.PlexIP} -c 5";
            }

            Dispatcher.BeginInvoke(new Action(delegate
            {
                txtOutput.AppendText($"{command}\n");
            }));
            try
            {
                cmdCurrent = linuxClient.CreateCommand(command);
                var asynch = cmdCurrent.BeginExecute();
                var reader = new StreamReader(cmdCurrent.OutputStream);

                while (!asynch.IsCompleted)
                {
                    if (workerEncode.CancellationPending)
                    {
                        return(false);
                    }
                    var result = reader.ReadLine();
                    if (string.IsNullOrEmpty(result))
                    {
                        continue;
                    }
                    if (result != null)
                    {
                        workerEncode.ReportProgress(0, result);
                    }
                    reader.DiscardBufferedData();
                    Thread.Sleep(750);
                }
                cmdCurrent.EndExecute(asynch);
                cmdCurrent = null;
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex.Message}", "ERROR", MessageBoxButton.OK);
                return(false);
            }
        }
Example #27
0
        private void Arrange()
        {
            var random = new Random();

            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock <IChannelSession>(MockBehavior.Strict);
            _commandText        = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding           = Encoding.UTF8;

            var seq = new MockSequence();

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _sshCommand.BeginExecute();
        }
Example #28
0
        // ---------------- Properties ----------------

        // ---------------- Functions ----------------

        /// <summary>
        /// Runs the SSH process.
        /// </summary>
        /// <returns>The exit code of the process.</returns>
        public int RunSsh(CancellationToken cancelToken)
        {
            this.config.Validate();

            this.lockFileManager.CreateLockFile();
            using (SshClient client = new SshClient(this.config.Server, this.config.Port, this.config.UserName, this.config.Password))
            {
                client.Connect();
                this.logger.WarningWriteLine(2, "Client Version: " + client.ConnectionInfo.ClientVersion);
                this.logger.WarningWriteLine(2, "Server Version: " + client.ConnectionInfo.ServerVersion);

                using (SshCommand command = client.CreateCommand(this.config.Command))
                {
                    IAsyncResult task = command.BeginExecute();

                    // Using tasks seems to print things to the console better; it doesn't all just bunch up at the end.
                    Task stdOutTask = AsyncWriteToStream(Console.OpenStandardOutput, command.OutputStream, task, "STDOUT", cancelToken);
                    Task stdErrTask = AsyncWriteToStream(Console.OpenStandardError, command.ExtendedOutputStream, task, "STDERR", cancelToken);

                    try
                    {
                        Task[] tasks = new Task[] { stdOutTask, stdErrTask };
                        Task.WaitAll(tasks, cancelToken);
                    }
                    catch (OperationCanceledException)
                    {
                        this.logger.WarningWriteLine(1, "Cancelling Task...");
                        command.CancelAsync();
                        this.logger.WarningWriteLine(1, "Task Cancelled");
                        this.lockFileManager.DeleteLockFile();
                        throw;
                    }

                    command.EndExecute(task);

                    int exitStatus = command.ExitStatus;

                    this.logger.WarningWriteLine(1, "Process exited with exit code: " + exitStatus);

                    this.lockFileManager.DeleteLockFile();
                    return(exitStatus);
                }
            }
        }
        public override Dictionary <AuditFileInfo, string> ReadFilesAsText(List <AuditFileInfo> files)
        {
            CallerInformation here = this.Here();
            Dictionary <AuditFileInfo, string> results = new Dictionary <AuditFileInfo, string>(files.Count);
            object    results_lock = new object();
            Stopwatch sw           = new Stopwatch();

            sw.Start();
            Parallel.ForEach(files, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 20
            }, (_f, state) =>
            {
                SshCommand cmd = this.SshClient.CreateCommand("cat " + _f.FullName);
                Stopwatch cs   = new Stopwatch();
                cs.Start();
                CommandAsyncResult result = cmd.BeginExecute(new AsyncCallback(SshCommandAsyncCallback), new KeyValuePair <SshCommand, Stopwatch> (cmd, cs)) as CommandAsyncResult;
                cmd.EndExecute(result);
                KeyValuePair <SshCommand, Stopwatch> s = (KeyValuePair <SshCommand, Stopwatch>)result.AsyncState;
                if (s.Key.Result != string.Empty)
                {
                    lock (results_lock)
                    {
                        results.Add(_f, s.Key.Result);
                    }
                    if (s.Value.IsRunning)
                    {
                        s.Value.Stop();
                    }
                    Debug(here, "Read {0} chars from {1}.", s.Key.Result.Length, _f.FullName);
                    Progress("Read environment files", files.Count, 3, s.Value.Elapsed);
                }
                else
                {
                    Error(here, "Could not read {0} as text. Command returned: {1}", _f.FullName, s.Key.Error);
                }
                s.Key.Dispose();
                cs = null;
            });
            sw.Stop();
            Success("Read text for {0} out of {1} files in {2} ms.", results.Count(r => r.Value.Length > 0), results.Count(), sw.ElapsedMilliseconds);
            return(results);
        }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock <IChannelSession>(MockBehavior.Strict);
            _commandText        = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding           = Encoding.UTF8;
            _expectedExitStatus = random.Next();
            _dataA         = random.Next().ToString(CultureInfo.InvariantCulture);
            _dataB         = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataA = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataB = random.Next().ToString(CultureInfo.InvariantCulture);
            _asyncResult   = null;

            var seq = new MockSequence();

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
            .Returns(true)
            .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionMock.InSequence(seq).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(seq).Setup(p => p.Close());
            _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand  = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResult = _sshCommand.BeginExecute();

            _channelSessionMock.Raise(c => c.DataReceived += null,
                                      new ChannelDataEventArgs(0, _encoding.GetBytes(_dataA)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                                      new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataA), 0));
            _channelSessionMock.Raise(c => c.DataReceived += null,
                                      new ChannelDataEventArgs(0, _encoding.GetBytes(_dataB)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                                      new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataB), 0));
            _channelSessionMock.Raise(c => c.RequestReceived += null,
                                      new ChannelRequestEventArgs(new ExitStatusRequestInfo((uint)_expectedExitStatus)));
        }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;
            _expectedExitStatus = random.Next();
            _dataA = random.Next().ToString(CultureInfo.InvariantCulture);
            _dataB = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataA = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataB = random.Next().ToString(CultureInfo.InvariantCulture);
            _asyncResult = null;

            var seq = new MockSequence();
            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
                .Returns(true)
                .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionMock.InSequence(seq).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(seq).Setup(p => p.Close());
            _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResult = _sshCommand.BeginExecute();

            _channelSessionMock.Raise(c => c.DataReceived += null,
                new ChannelDataEventArgs(0, _encoding.GetBytes(_dataA)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataA), 0));
            _channelSessionMock.Raise(c => c.DataReceived += null,
                new ChannelDataEventArgs(0, _encoding.GetBytes(_dataB)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataB), 0));
            _channelSessionMock.Raise(c => c.RequestReceived += null,
                new ChannelRequestEventArgs(new ExitStatusRequestInfo((uint) _expectedExitStatus)));
        }
Example #32
0
        public int Execute(string command, Stream stdin = null, Stream stdout = null, Stream stderr = null, int timeout = 0, bool throwOnNonZero = false)
        {
            SshCommand sshCommand = sshClient.CreateCommand(command);

            if (timeout > 0)
            {
                sshCommand.CommandTimeout = new TimeSpan(0, 0, 0, 0, timeout);
            }

            IAsyncResult execResult = sshCommand.BeginExecute(null, null, stdout, stderr);

            if (stdin != null)
            {
                try
                {
                    stdin.Seek(0, SeekOrigin.Begin);
                }
                catch
                {
                    // no-op
                }

                sshCommand.SendData(stdin);
            }

            sshCommand.EndExecute(execResult);

            if (sshCommand.ExitStatus != 0 && throwOnNonZero)
            {
                throw new SshClientException(string.Format("Shell command \"{0}\" returned exit code {1} {2}", command, sshCommand.ExitStatus, sshCommand.Error));
            }

#if DEBUG
            Debug.WriteLine(string.Format("{0} # exit code {1}", command, sshCommand.ExitStatus));
#endif

            return(sshCommand.ExitStatus);
        }
Example #33
0
        public IEnumerator IECommand(string command)
        {
            if (client == null)
            {
                Debug.LogError("NOT Connected Server");
                yield break;
            }

            Debug.Log("Start IEnumerator");

            SshCommand cmd = client.CreateCommand(command);

            var asyncCmd     = cmd.BeginExecute();
            var stdoutReader = new StreamReader(cmd.OutputStream);
            var stderrReader = new StreamReader(cmd.ExtendedOutputStream);

            while (!asyncCmd.IsCompleted)
            {
                string line = stdoutReader.ReadToEnd();
                if (!string.IsNullOrEmpty(line))
                {
                    successEvent.Invoke(line);
                }
                line = stderrReader.ReadToEnd();
                if (!string.IsNullOrEmpty(line))
                {
                    failureEvent.Invoke(line);
                }

                yield return(null);
            }
            cmd.EndExecute(asyncCmd);

            stdoutReader.Dispose();
            stderrReader.Dispose();

            Debug.Log("End IEnumerator");
        }
Example #34
0
        public string SSH_Command(string Command)
        {
            sshclient = new SshClient("127.0.0.1", "root", "alpine");
            string text = "";

            try
            {
                ((Thread)(object)sshclient).Start();
                SshCommand   sshCommand  = sshclient.CreateCommand(Command);
                IAsyncResult asyncResult = sshCommand.BeginExecute();
                while (!asyncResult.IsCompleted)
                {
                    Thread.Sleep(200);
                }
                text = sshCommand.EndExecute(asyncResult);
                ((Thread)(object)sshclient).Start();
            }
            catch (Exception ex)
            {
                ERROR = ((TextReader)(object)ex).ReadToEnd();
                text  = "Failed";
            }
            return(text);
        }