Ejemplo n.º 1
0
        private void TerminalKeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (!Connected)
            {
                return;
            }

            var controlPressed = (Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down));
            var shiftPressed   = (Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down));

            switch (e.Key)
            {
            case Windows.System.VirtualKey.Shift:
            case Windows.System.VirtualKey.Control:
                return;

            default:
                break;
            }

            if (controlPressed && e.Key == Windows.System.VirtualKey.F12)
            {
                Terminal.Debugging = !Terminal.Debugging;
            }

            if (controlPressed && e.Key == Windows.System.VirtualKey.F10)
            {
                Consumer.SequenceDebugging = !Consumer.SequenceDebugging;
            }

            if (controlPressed && e.Key == Windows.System.VirtualKey.F11)
            {
                ViewDebugging = !ViewDebugging;
                canvas.Invalidate();
            }

            var code = Terminal.GetKeySequence((controlPressed ? "Ctrl+" : "") + (shiftPressed ? "Shift+" : "") + e.Key.ToString());

            if (code != null)
            {
                Task.Run(() =>
                {
                    _stream.Write(code, 0, code.Length);
                    _stream.Flush();
                });

                e.Handled = true;

                if (ViewTop != Terminal.ViewPort.TopRow)
                {
                    Terminal.ViewPort.SetTopLine(ViewTop);
                    canvas.Invalidate();
                }
            }

            //System.Diagnostics.Debug.WriteLine(e.Key.ToString() + ",S" + (shiftPressed ? "1" : "0") + ",C" + (controlPressed ? "1" : "0"));
        }
Ejemplo n.º 2
0
        private void button3_Click(object sender, EventArgs e)
        {
            aTimer          = new System.Windows.Forms.Timer();
            aTimer.Interval = 5000;
            aTimer.Tick    += new EventHandler(timer_tick);
            aTimer.Start();

            Monitering_sShell.Write("cat /proc/meminfo | grep MemTotal \n");
            Monitering_sShell.Flush();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Executes an asynchronous command
        /// </summary>
        /// <param name="csentry">The CSEntryChange to apply to this command</param>
        /// <param name="result">The result object for the current operation</param>
        /// <param name="command">The definition of the command to execute</param>
        private static void ExecuteAsyncCommand(CSEntryChange csentry, OperationResult result, AsyncCommand command)
        {
            string output = string.Empty;

            try
            {
                ShellStream shell = client.CreateShellStream("lithnet.sshma", 80, 24, 800, 600, 1024);
                output += shell.ReadLine();

                foreach (AsyncCommandSend sendCommand in command.Commands)
                {
                    if (sendCommand is AsyncCommandSendExpect)
                    {
                        AsyncCommandSendExpect expectCommand = sendCommand as AsyncCommandSendExpect;
                        string   expectText = expectCommand.Expect.ExpandDeclaration(csentry, false, false);
                        TimeSpan timeout    = new TimeSpan(0, 0, expectCommand.Timeout);

                        shell.Expect(
                            timeout,
                            new ExpectAction(
                                expectText,
                                (s) =>
                        {
                            System.Diagnostics.Debug.WriteLine(s);
                            output += s;
                            shell.Write(expectCommand.Command.ExpandDeclaration(csentry, false, false) + "\n");
                        }));
                    }
                    else
                    {
                        shell.Write(sendCommand.Command.ExpandDeclaration(csentry, false, false) + "\n");
                    }
                }

                if (command.ExpectSuccess != null)
                {
                    if (!string.IsNullOrWhiteSpace(command.ExpectSuccess.Expect.DeclarationText))
                    {
                        TimeSpan timeout = new TimeSpan(0, 0, command.ExpectSuccess.Timeout);
                        if (shell.Expect(command.ExpectSuccess.Expect.ExpandDeclaration(csentry, false, false), timeout) == null)
                        {
                            throw new ExtensibleExtensionException("The asynchronous command did not return the expected result");
                        }
                    }
                }
            }
            finally
            {
                Logger.WriteLine("Shell session log:", LogLevel.Debug);
                Logger.WriteLine(output, LogLevel.Debug);
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Send data to ssh client
 /// </summary>
 /// <param name="byteData"></param>
 private static void SendSSHClientData(byte[] byteData)
 {
     try
     {
         shellStream.Write(byteData, 0, byteData.Length);
         shellStream.Flush();
     }
     catch (Exception e)
     {
         Trace.TraceError("Failed to send data to ssh client, remote session {0} ({1})", RemoteSessionID, e);
         throw;
     }
 }
        static void Main(string[] args)
        {
            var host     = "";
            var user     = "";
            var key_file = @"";

            using (var client = new SshClient(host, user, new PrivateKeyFile(key_file)))
            {
                int timoutCounter = 0;
                do
                {
                    timoutCounter++;
                    try { client.Connect(); }
                    catch (Exception e)
                    {
                        Console.WriteLine("Connection error: " + e.Message);
                    }
                } while (!client.IsConnected);

                ShellStream stream = client.CreateShellStream("shell", 200, 24, 1920, 1080, 4096);

                // starts the process on remote ssh server
                stream.WriteLine("dotnet ~/Remote/Remote.dll");

                var cancel_source  = new CancellationTokenSource();
                var output_handler = new OutputHandler(stream);
                var output_thread  = output_handler.RunOnNewThread(cancel_source.Token);

                while (true)
                {
                    var key = Console.ReadKey();

                    if (key.KeyChar == 'x')
                    {
                        break;
                    }
                    else
                    {
                        stream.Write(key.KeyChar.ToString());
                    }
                }

                cancel_source.Cancel();

                stream.Write("q");

                client.Disconnect();

                output_thread.Join();
            }
        }
Ejemplo n.º 6
0
        private string _SendCommand(string ip, string id, string password, string command)
        {
            string ret = "";

            Console.WriteLine("\n[ start ]");
            try
            {
                // 연결 체크
                if ((CommandView.current.sshclient == null || !CommandView.current.sshclient.IsConnected) ||
                    (CommandView.current.sshclient.ConnectionInfo.Host != ip ||
                     CommandView.current.sshclient.ConnectionInfo.Port != PORT ||
                     CommandView.current.sshclient.ConnectionInfo.Username != id))
                {
                    if (CommandView.current.sshclient != null && CommandView.current.sshclient.IsConnected)
                    {
                        CommandView.current.sshclient.Disconnect();
                    }

                    CommandView.current.sshclient = new SshClient(ip, PORT, id, password);
                    CommandView.current.sshclient.Connect();
                    shell_stream = sshclient.CreateShellStream("customCommand", 80, 24, 800, 600, 1024);
                    timer_read.Start();

                    Console.Write("[ ReConnection ] ");
                    Console.WriteLine(CommandView.current.sshclient.ConnectionInfo.Host + " / " + CommandView.current.sshclient.ConnectionInfo.Port + " / " + CommandView.current.sshclient.ConnectionInfo.Username + " / " + CommandView.current.sshclient.ConnectionInfo.ProxyUsername + " / " + CommandView.current.sshclient.ConnectionInfo.ProxyPassword);
                }
                // send
                if (shell_stream != null)
                {
                    shell_stream.Write(command);
                    shell_stream.Write("\n");
                    shell_stream.Flush();
                    //textBox_result.Text += read2();
                }
            }
            catch (Exception ex)
            {
                ret = "Error = " + ex.Message;
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("[ finish ]\n");

            if (command == "exit")
            {
                CommandView.current.sshclient.Disconnect();
            }
            return(ret);
        }
        private string RunShellCommand(ShellStream Stream, string CommandLine, bool ExpectRootPrompt)
        {
            System.Console.Out.WriteLine("CL$ " + CommandLine);

            Stream.WriteLine(CommandLine);

            string Response = "";

            bool End = false;

            while (!End)
            {
                Stream.Expect(
                    new ExpectAction(new Regex(@"\w+@\w+\:[\w~\/\\]+\$"), (Input) =>
                {
                    End       = true;
                    Response += Input;
                }),
                    new ExpectAction(new Regex(@"\w+@\w+\:[\w~\/\\]+#"), (Input) =>
                {
                    End       = true;
                    Response += Input;
                }),
                    new ExpectAction(new Regex(@"\n\:"), (Input) =>
                {
                    Response += Input;
                    Stream.Write(" ");
                })
                    );
            }

            System.Console.Out.WriteLine(Response);

            return(Response);
        }
Ejemplo n.º 8
0
        void sshterm()
        {
            PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod("root", @"Mr\6(atn2).F");
            ConnectionInfo connectionInfo      = new ConnectionInfo("192.168.197.100", 22, "root", pauth);
            SshClient      client = new SshClient(connectionInfo);

            client.Connect();
            string reply = string.Empty;

            shellStream = client.CreateShellStream("dumb", 80, 24, 800, 600, 1024);
            sread       = new StreamReader(shellStream);
            shellStream.DataReceived += DataReceivedEventHandler;
            Console.CancelKeyPress   += CtlCEventHandler;
            ConsoleKeyInfo keyInfo;
            String         output;

            while (client.IsConnected)
            {
                keyInfo = Console.ReadKey(true);

                output = keyInfo.KeyChar.ToString();
                if (keyInfo.Modifiers == ConsoleModifiers.Control && keyInfo.Key == ConsoleKey.T)
                {
                }
                shellStream.Write(output);
            }
        }
Ejemplo n.º 9
0
        public IEnumerable <string> ExecuteCommand(string command)
        {
            lock (_lock)
            {
                if (!Connected)
                {
                    Connect();
                    if (!Connected)
                    {
                        return(null);
                    }
                }

                //Split Write and WriteLine as it looked like WriteLine was truncating commands
                _shellStream.Write(command);
                _shellStream.WriteLine("");

                string streamOutput = _shellStream.Expect(new Regex(_terminalPrompt));
                Debug.Assert(!string.IsNullOrEmpty(streamOutput));

                using (StringReader sr = new StringReader(streamOutput))
                {
                    var    result = new List <string>();
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        result.Add(line);
                    }

                    return(result);
                }
            }
        }
Ejemplo n.º 10
0
 private void textBox6_KeyPress(object sender, KeyPressEventArgs e)
 {
     try
     {
         if (e.KeyChar == 13)
         {
             Command_sShell.Write(textBox6.Text + "\n");
             Command_sShell.Flush();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         Console.WriteLine(ex.StackTrace);
     }
 }
Ejemplo n.º 11
0
        private void SerialDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string Buffer;


            Buffer = m_Serial.ReadExisting();
            m_SSHStream.Write(Buffer);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Sends text to the server
 /// </summary>
 /// <param name="text"></param>
 public void SendText(string text)
 {
     try
     {
         if (Client != null)
         {
             TheStream.Write(text);
             TheStream.Flush();
         }
     }
     catch
     {
         Debug.Console(1, this, "Stream write failed. Disconnected, closing");
         ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY;
         HandleConnectionFailure();
     }
 }
Ejemplo n.º 13
0
        public void ShellSend(Gdk.Key key)
        {
            if (UserInputMode)
            {
                LastKeyPress = key;
                userkeypress.Set();
            }
            else
            {
                if (LocalEcho)
                {
                    Write(key.ToString());
                }
                if (shellStream != null && shellStream.CanWrite)
                {
                    byte[] charBytes = null;

                    switch (key)
                    {
                    case Gdk.Key.Shift_L:
                    case Gdk.Key.Shift_R:
                    case Gdk.Key.ISO_Level3_Shift:     //Alt Gr
                        //Ignore
                        break;

                    case Gdk.Key.Return:
                    case Gdk.Key.KP_Enter:
                        charBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
                        break;

                    case Gdk.Key.BackSpace:
                        charBytes = new byte[] { (byte)'\b' };
                        break;

                    case Gdk.Key.KP_Tab:
                    case Gdk.Key.Tab:
                        charBytes = new byte[] { (byte)'\t' };
                        break;

                    case Gdk.Key.Escape:
                        charBytes = new byte[] { 0x1B };     //ESC
                        break;

                    default:
                        charBytes = Encoding.UTF8.GetBytes(new char[] { key.GetChar() });
                        break;
                    }

                    if (charBytes != null)
                    {
                        shellStream.Write(charBytes, 0, charBytes.Length);
                        shellStream.Flush();
                    }
                }
            }
        }
Ejemplo n.º 14
0
 public void SendBytes(byte[] data)
 {
     if (STDMode)
     {
         SshShell.Write(data, 0, data.Length);
     }
     else
     {
         throw new InvalidOperationException("STD mode only");
     }
 }
Ejemplo n.º 15
0
        private static void WriteSecure(SecureString secureString, ShellStream writer)
        {
            IntPtr unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);

            try
            {
                byte[] buf = new byte[2];
                for (int i = 0; i < secureString.Length * 2;)
                {
                    buf[0] = Marshal.ReadByte(unmanagedString, i++);
                    buf[1] = Marshal.ReadByte(unmanagedString, i++);
                    writer.Write(BitConverter.ToChar(buf).ToString());
                }
                writer.Write("\n");
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }
Ejemplo n.º 16
0
        private static void sendCommand(string command)
        {
            //BackgroundReConnector.RunWorkerAsync();
            LinuxTreeViewItem.ReConnect();

            try
            {
                // send
                if (shell_stream != null)
                {
                    shell_stream.Write(command);
                    shell_stream.Write("\n");
                    shell_stream.Flush();
                    Log.Print(command, "send command" /*, Home.m_wnd.richTextBox_status*/);
                }
            }
            catch (Exception ex)
            {
                Log.PrintError(ex.Message, "send command", Home.m_wnd.richTextBox_status);
            }
        }
Ejemplo n.º 17
0
        private void TextBox_input_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }


            //var x = client.RunCommand(textBox_input.Text);
            //Console.WriteLine(x.Result);
            //textBox_result.Text += SendCommand(stream, textBox_input.Text);
            if (sshClient.IsConnected)
            {
                stream.Write(textBox_input.Text);
                stream.Write("\n");
                stream.Flush();
                string str = read();
                textBox_result.Text += str;
                //string str;
                //while((str = stream.ReadLine()) != null)
                //{
                //	Console.WriteLine("read" + str);
                //}
            }
            //input.Write(textBox_input.Text);
            //input.Flush();

            //if(input != null)
            //	Console.WriteLine("input = " + input.Read());
            //if(output != null)
            //	Console.WriteLine("output = " + output.Read());
            //if(exoutput != null)
            //	Console.WriteLine("exoutput = " + exoutput.Read());

            //textBox_input.Text = "";
            //textBox_result.Text += "result\n" + output.Read() + "\n";


            textBox_input.Text = "";
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Sends text to the server
        /// </summary>
        /// <param name="text"></param>
        public void SendText(string text)
        {
            try
            {
                if (Client != null)
                {
                    if (StreamDebugging.TxStreamDebuggingIsEnabled)
                    {
                        Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, text);
                    }

                    TheStream.Write(text);
                    TheStream.Flush();
                }
            }
            catch
            {
                Debug.Console(1, this, "Stream write failed. Disconnected, closing");
                ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY;
                HandleConnectionFailure();
            }
        }
Ejemplo n.º 19
0
        public String expect(String cmd, int t)
        {
            String retval = "";

            try
            {
                stream.Write(cmd + "\r");
                stream.Flush();
                Thread.Sleep(t);
                retval = stream.Expect(reg_prompt, waitTime);
                stream.Flush();
                while (stream.DataAvailable == true)
                {
                    retval += stream.Read();
                }
                return(retval);
            }
            catch (System.Exception e)
            {
                return(retval + "\n" + "err: " + e.ToString());
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Send data to ssh client
 /// </summary>
 /// <param name="byteData"></param>
 private static void SendSSHClientData(byte[] byteData)
 {
     try
     {
         shellStream.Write(byteData, 0, byteData.Length);
         shellStream.Flush();
     }
     catch (Exception e)
     {
         pipeMessaging.ClosePipes();
         DisconnectSSHClient();
     }
 }
Ejemplo n.º 21
0
        private static void sendCommand(string command)
        {
            //LinuxTreeViewItem.ReconnectServer();
            //LinuxTreeViewItem.ReConnect();
            LinuxTreeViewItem.ReConnect(1000);

            try
            {
                // send
                if (shell_stream != null)
                {
                    shell_stream.Write(command);
                    shell_stream.Write("\n");
                    shell_stream.Flush();
                    Log.Print(command, "send command" /*, test4.m_wnd.richTextBox_status*/);
                }
            }
            catch (Exception ex)
            {
                Log.PrintError(ex.Message, "send command", WindowMain.m_wnd.richTextBox_status);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Wrtites a msg to the SSH stream
        /// </summary>
        /// <param name="msg">msg to send</param>
        /// <returns></returns>
        public uint Send(RSProtoBuffSSHMsg msg)
        {
            System.Diagnostics.Debug.WriteLineIf(DEBUG, "send: sending packet " + msg.ReqID + " MsgID: " + msg.MsgID + " body size: " + msg.BodySize);
            if (_stream.CanWrite)
            {
                try
                {
                    _stream.Write(CreatePacketFromMsg(msg), 0, 16 + (int)msg.BodySize);
                    _stream.Flush();
                }
                catch (Exception e)
                {
                    _parent.Error(e, RSRPC.ErrorFrom.ProtoBuf);
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("send: can't write stream");
                _parent.Error(new IOException("send: can't write stream"), RSRPC.ErrorFrom.ProtoBuf);
            }

            return(msg.ReqID);
        }
        /// <summary>
        /// Runs pre and post deployment commands over the SSH client.
        /// </summary>
        /// <param name="shellStream">The shell stream.</param>
        /// <param name="verbOptions">The verb options.</param>
        private static void RunShellStreamCommand(ShellStream shellStream, CliExecuteOptionsBase verbOptions)
        {
            var commandText = verbOptions.PostCommand;

            if (string.IsNullOrWhiteSpace(commandText))
            {
                return;
            }

            Terminal.WriteLine("    Executing shell command.", ConsoleColor.Green);
            shellStream.Write($"{commandText}\r\n");
            shellStream.Flush();
            Terminal.WriteLine($"    TX: {commandText}", ConsoleColor.DarkYellow);
        }
Ejemplo n.º 24
0
        public string ExecuteCommands(List <string> commands, string expactString)
        {
            string result = "";

            try
            {
                using (SshClient sshclient = new SshClient(_ConnectionInfo))
                {
                    sshclient.Connect();

                    using (ShellStream stream = sshclient.CreateShellStream("session", 512, 96, 800, 600, 8191))
                    {
                        stream.ErrorOccurred += (e, s) =>
                        {
                            Debug.WriteLine(s.Exception);
                        };

                        stream.Expect(new Regex(expactString));

                        foreach (string command in commands)
                        {
                            string logfile = string.Format("/var/tmp/firefly/{0}.log", Guid.NewGuid());
                            stream.Write(string.Format("{0} > {1}\n", command, logfile));
                            result += DownloadFileToMemory(logfile);
                            stream.Expect(new Regex(expactString));
                            stream.Write(string.Format("{0} {1}\n", "rm", logfile));
                            stream.Expect(new Regex(expactString));
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return(result);
        }
        private void Arrange()
        {
            SetupData();
            CreateMocks();
            SetupMocks();

            _shellStream = new ShellStream(_sessionMock.Object,
                                           _terminalName,
                                           _widthColumns,
                                           _heightRows,
                                           _widthPixels,
                                           _heightPixels,
                                           _terminalModes,
                                           _bufferSize);

            _shellStream.Write(_bufferData, 0, _bufferData.Length);
        }
Ejemplo n.º 26
0
        private void Tomcat_LogCommad()
        {
            if (cSSH_TomCat_Log1.IsConnected)
            {
                Tomcat_Log_sShell1.Write("tail -f " + textBox7.Text + listBox1.Items[1].ToString() + "/logs/catalina.out \n");
                Tomcat_Log_sShell1.Flush();
            }

            if (cSSH_TomCat_Log2.IsConnected)
            {
                Tomcat_Log_sShell2.Write("tail -f " + textBox7.Text + listBox1.Items[2].ToString() + "/logs/catalina.out \n");
                Tomcat_Log_sShell2.Flush();
            }

            if (cSSH_TomCat_Log3.IsConnected)
            {
                Tomcat_Log_sShell3.Write("tail -f " + textBox7.Text + listBox1.Items[3].ToString() + "/logs/catalina.out \n");
                Tomcat_Log_sShell3.Flush();
            }
        }
Ejemplo n.º 27
0
        private string ExecuteCommandUsingShellStream(ShellStream shell, string Command)
        {
            string       cmdResult = string.Empty;
            StreamReader reader    = new StreamReader(shell);

            shell.Flush();
            cmdResult = string.Empty;
            ExInfo   += ", Sending Command: " + Command;
            shell.Write(Command + "\n");
            cmdResult = reader.ReadToEnd();
            int   iCount = 1;
            Regex regExp = new Regex(@"ENTER ...|continue ...|option :|\> |\$ |\%");

            while (regExp.Matches(cmdResult.ToString()).Count == 0 && iCount < 20)
            {
                cmdResult += reader.ReadToEnd();

                cmdResult = Regex.Replace(cmdResult, @"[\u001b]\[[0-9]+m", "");
                Thread.Sleep(1000);
                iCount++;
            }
            return(cmdResult);
        }
 private void Act()
 {
     _shellStream.Write(_data, _offset, _count);
 }
Ejemplo n.º 29
0
 public void WriteTest1()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string terminalName = string.Empty; // TODO: Initialize to an appropriate value
     uint columns = 0; // TODO: Initialize to an appropriate value
     uint rows = 0; // TODO: Initialize to an appropriate value
     uint width = 0; // TODO: Initialize to an appropriate value
     uint height = 0; // TODO: Initialize to an appropriate value
     int maxLines = 0; // TODO: Initialize to an appropriate value
     IDictionary<TerminalModes, uint> terminalModeValues = null; // TODO: Initialize to an appropriate value
     ShellStream target = new ShellStream(session, terminalName, columns, rows, width, height, maxLines, terminalModeValues); // TODO: Initialize to an appropriate value
     string text = string.Empty; // TODO: Initialize to an appropriate value
     target.Write(text);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Ejemplo n.º 30
0
        public void SSHRunCommand(string command)
        {
            StringBuilder reply = new StringBuilder();

            ss.Flush();
            StreamReader sreader = new StreamReader(ss);

            sreader.ReadToEnd();
            if (command != "\u0003\n")
            {
                while (!sreader.EndOfStream)
                {
                    if (!this.IsDriverRunning)
                    {
                        break;
                    }
                    reply.AppendLine(sreader.ReadLine());
                    Thread.Sleep(1000);
                }
            }
            if (command.StartsWith("CHAR_"))
            {
                command = command.Replace("CHAR_", "").Replace("\n", "");
                try
                {
                    ss.WriteByte(System.Convert.ToByte(Convert.ToInt32(command)));
                }
                catch (Exception ex) { Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); }
            }
            else
            {
                ss.Write(command);
            }
            try
            {
                if (mWait == 0 || mWait == null)
                {
                    mWait = this.ImplicitWait;
                }
                if (mWait == 0)
                {
                    mWait = 30;
                }

                DateTime startingTime = DateTime.Now;
                bool     expOut       = false;
                Regex    regExp;
                mExpString = string.IsNullOrEmpty(mExpString) ? "" : mExpString;
                if (mExpString != "" && command != "\u0003\n")
                {
                    regExp = new Regex(@"~~~GINGER_RC_END~~~|" + mExpString);
                }
                else
                {
                    regExp = new Regex(@"\> |\$ |\% |assword: |\. |~~~GINGER_RC_END~~~");
                }

                while ((DateTime.Now - startingTime).TotalSeconds <= mWait && taskFinished != true)
                {
                    if (!this.IsDriverRunning)
                    {
                        break;
                    }

                    reply.AppendLine(sreader.ReadToEnd());
                    Thread.Sleep(1000);
                    if (regExp.Matches(reply.ToString()).Count > 0)
                    {
                        if (reply.ToString().Contains(command) && expOut == false)
                        {
                            taskFinished = true;
                            expOut       = true;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (sreader.EndOfStream)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }
                    if ((DateTime.Now - startingTime).TotalSeconds >= mWait)
                    {
                        taskFinished = true;
                        break;
                    }
                }
                if (command != "\u0003\n")
                {
                    mConsoleDriverWindow.ConsoleWriteText(reply.ToString(), true);
                    reply.Clear();
                }
                taskFinished = true;
            }
            catch (Exception ex)
            {
                Reporter.ToLog(eLogLevel.ERROR, ex.Message);
            }
            mConsoleDriverWindow.ConsoleWriteText(reply.ToString(), true);
            reply.Clear();
        }
Ejemplo n.º 31
0
        public static void HandleInput(string input, object sender = null)
        {
            sender = Program.sender ?? sender;
            StartupForm form = null;

            if (sender != null)
            {
                form = (StartupForm)sender;
                form.prgBar.Style = ProgressBarStyle.Blocks;
                form.prgBar.Value = 0;
            }
            string[] args = input.Split(' ');
            switch (args[0].ToLower())
            {
                #region "help"
            case "help":
                Help();
                break;

                #endregion
                #region "connect"
            case "connect":
                if (form != null)
                {
                    form.prgBar.Maximum = 6;
                }
                try
                {
                    host = args[1]; if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                    Settings.Default.host = host; if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                    username = args[2]; if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                    password = args[3]; if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                }
                catch (IndexOutOfRangeException) { }
                connection = new SshClient(
                    host: host,
                    username: username,
                    password: password);    if (form != null)
                {
                    form.prgBar.Value++;
                }
                connection.Connect();   if (form != null)
                {
                    form.prgBar.Value++;
                }
                if (sender == null)
                {
                    Console.WriteLine($"Connected to {host}'s user {username} with password {new string('*', password.Length)}");
                }
                username = "******";
                password = "******";
                break;

                #endregion
                #region "disconnect"
            case "disconnect":
                if (form != null)
                {
                    form.prgBar.Maximum = 1;
                }
                connection.Disconnect();    if (form != null)
                {
                    form.prgBar.Value++;
                }
                break;

                #endregion
                #region "shutdown"
            case "shutdown":
                if (form != null)
                {
                    form.prgBar.Maximum = 3;
                }
                using (ShellStream shellStream = connection.CreateShellStream("xterm", 255, 50, 800, 600, 1024,
                                                                              new Dictionary <Renci.SshNet.Common.TerminalModes, uint>()))
                {
                    shellStream.Write("sudo poweroff\n");   if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                    shellStream.Expect($"[sudo] password for {username}:"); if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                    shellStream.Write($"{password}\n"); if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                }
                break;

                #endregion
                #region "gui"
            case "gui":
                FormTools.RunInNewThread(new StartupForm(), true);
                break;

                #endregion
                #region "ssh"
            case "ssh":
                if (form != null)
                {
                    form.prgBar.Maximum = 2;
                }
                using (ShellStream shellStream = connection.CreateShellStream("xterm", 255, 50, 800, 600, 2048,
                                                                              new Dictionary <Renci.SshNet.Common.TerminalModes, uint>()))
                {
                    Console.WriteLine(); if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                    Console.Write(shellStream.Read()); if (form != null)
                    {
                        form.prgBar.Value++;
                    }
                    if (form != null)
                    {
                        form.prgBar.Style = ProgressBarStyle.Marquee;
                    }
                    while (true)
                    {
                        string streamInput = Console.ReadLine();
                        if (streamInput == "exit")
                        {
                            break;
                        }
                        shellStream.WriteLine(streamInput);
                        Console.Write(shellStream.Read().TrimStart(streamInput.ToCharArray()));
                    }
                }
                break;

                #endregion
                #region motor
            case "motor":
                HardwareController.MoveMotor(address: args[1], action: args[2]);
                break;

                #endregion
            case "run":
                if (HardwareController.State)
                {
                    HardwareController.MoveMotor(HardwareController.MotorList["outB"], MotorMoveActions.run_forever);
                }
                break;

            case "": break;

            default:
                throw new NotSupportedException($"Unsupported Command: {input}");
            }
        }