public static string TerminalExecute(string cmd, string password) { IDictionary <Renci.SshNet.Common.TerminalModes, uint> modes = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>(); modes.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53); ShellStream shellStream = client.CreateShellStream("xterm", 280, 24, 800, 600, 1024, modes); var output = shellStream.Expect(new Regex(@"[$>]")); log.Info(string.Format("Execution Reply: \t{0}", output)); log.Info(string.Format("Sending Text :{0}", cmd)); shellStream.WriteLine(cmd); output = shellStream.Expect(new Regex(@"([$#>:])")); log.Info(string.Format("Execution Reply: \t{0}", output)); log.Info(string.Format("Sending Text:{0}", password)); shellStream.WriteLine(password); output = shellStream.Expect(new Regex(@"([$#>:])")); log.Info(string.Format("Execution Reply: \t{0}", output)); output = shellStream.Read(); log.Info(string.Format("End Execution Reply: \t{0}", output)); return(output); }
/// <summary> /// Read text that is sitting in the buffer. But don't do it until /// the computer has had a chance to dump it. There is a hardwired 10 second /// wait for the first text to show up. /// </summary> /// <param name="shell">The shell stream to look for text</param> /// <param name="msToWaitAfterText">How long to wait after text appears in the buffer before reading everything.</param> /// <returns></returns> public static async Task <string> ReadRemainingText(this ShellStream shell, int msToWaitAfterText) { var timeout = DateTime.Now + TimeSpan.FromSeconds(10); while (shell.Length == 0 && timeout > DateTime.Now) { Thread.Sleep(20); } if (shell.Length == 0) { throw new InvalidOperationException("Waited 10 seconds for any output from shell; nothing seen. Possible hang?"); } await Task.Delay(msToWaitAfterText); // Sometimes two lines are sent. No idea why. var r = shell.ReadLine(TimeSpan.FromMilliseconds(1)); if (r != null && r.Length > 0) { return(r); } else { return(shell.Read()); } }
void thrRead() { byte[] buffer = new byte[1024]; while (true) { int count = ss.Read(buffer, 0, buffer.Length); if (count != 0) { string txt = Encoding.ASCII.GetString(buffer, 0, count); var lines = txt.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var l in lines) { if (l.EndsWith("# ") || l.EndsWith("#")) { evt.Set(); } } Console.Write(txt); } else { Thread.Sleep(1); } } }
private void SSHDataReceived(object sender, Renci.SshNet.Common.ShellDataEventArgs e) { string Buffer; Buffer = m_SSHStream.Read(); m_Serial.Write(Buffer); }
private void Tick(object sender, EventArgs e) { if (_data == null || !_data.CanRead || PacketReceived == null) { return; } // Try to read some data from the COM port and append it to our localBuffer. // If there's an IOException then the device has been disconnected. try { int readCount = (int)_data.Length; if (quickDisconnect && readCount < 1) { numNoReads++; if (numNoReads == 10) { throw new SSHMonitorDisconnectException(); } return; } numNoReads = 0; byte[] readBuffer = new byte[readCount]; _ = _data.Read(readBuffer, 0, readCount); _localBuffer.AddRange(readBuffer); } catch (IOException) { Stop(); Disconnected?.Invoke(this, EventArgs.Empty); return; } // Try and find 2 splitting characters in our buffer. int lastSplitIndex = _localBuffer.LastIndexOf(0x0A); if (lastSplitIndex <= 1) { return; } int sndLastSplitIndex = _localBuffer.LastIndexOf(0x0A, lastSplitIndex - 1); if (lastSplitIndex == -1) { return; } // Grab the latest packet out of the buffer and fire it off to the receive event listeners. int packetStart = sndLastSplitIndex + 1; int packetSize = lastSplitIndex - packetStart; PacketReceived(this, new PacketDataEventArgs(_localBuffer.GetRange(packetStart, packetSize).ToArray())); // Clear our buffer up until the last split character. _localBuffer.RemoveRange(0, lastSplitIndex); }
//async Task<string> read() string read() { int size_buffer = 4096; byte[] buffer = new byte[size_buffer]; int cnt = shell_stream.Read(buffer, 0, size_buffer); return(Encoding.UTF8.GetString(buffer, 0, cnt)); }
private static string read() { int size_buffer = 4096; byte[] buffer = new byte[size_buffer]; try { int cnt = shell_stream.Read(buffer, 0, size_buffer); read_line_ssh += Encoding.UTF8.GetString(buffer, 0, cnt); if (read_line_ssh.Length > 0) { //Log.Print(read_line_ssh, "read"/*, test4.m_wnd.richTextBox_status*/); int idx_newline = 0; if ((idx_newline = read_line_ssh.IndexOf('\n')) >= 0) { string line = read_line_ssh.Substring(0, idx_newline); for (int i = 0; i < view_log_start.Length; i++) { if (line.Length > view_log_start[i].Length && line.Substring(0, view_log_start[i].Length).ToLower() == view_log_start[i]) { Log.ViewMessage(line, view_message_caption, WindowMain.m_wnd.richTextBox_status); } } for (int i = 0; i < view_error_start.Length; i++) { if (line.Length > view_error_start[i].Length && line.Substring(0, view_error_start[i].Length).ToLower() == view_error_start[i]) { Log.PrintError(line, view_message_caption, WindowMain.m_wnd.richTextBox_status); } } Log.Print(line, "Read"); read_line_ssh = read_line_ssh.Substring(idx_newline + 1); } } } catch (Exception e) { Log.PrintError(e.Message, "read", WindowMain.m_wnd.richTextBox_status); } return(read_line_ssh); }
/// <summary> /// Reads bytes from the SSH stream /// </summary> /// <param name="timeOut">timeout in ms</param> /// <param name="length">how many bytes</param> /// <param name="output">byte array (out)</param> /// <returns>success?</returns> private bool ReadFromStream(uint timeOut, uint length, out byte[] output) { bool done = false; output = new byte[length]; byte[] dynBuffer; uint streamLength = 0; int read = 0, toRead = 0; DateTime timeOutTime = DateTime.Now.AddMilliseconds(timeOut); while (DateTime.Now < timeOutTime && read < length && !done) { if (_stream.DataAvailable) { // get stream length and calculate how many bytes we can read streamLength = (uint)_stream.Length; toRead = (int)Math.Min(length - read, streamLength); // setup buffer dynBuffer = new byte[toRead]; try { //read _stream.Read(dynBuffer, 0, toRead); } catch (Exception e) { //System.Diagnostics.Debug.WriteLineIf(DEBUG, "Error while reading"); _parent.Error(e, RSRPC.ErrorFrom.ProtoBuf); return(false); } // copy to target array Array.Copy(dynBuffer, 0, output, read, toRead); read += toRead; if (read == length) { done = true; } // we got data - reset timeout timeOutTime = DateTime.Now.AddMilliseconds(timeOut); } } if (!done) { System.Diagnostics.Debug.WriteLineIf(DEBUG, "rec: Could not read everything"); return(false); } return(true); }
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()); } }
public byte[] ReadBytes(int length) { if (STDMode) { byte[] buf = new byte[length]; SshShell.Read(buf, 0, length); return(buf); } else { throw new InvalidOperationException("STD mode only"); } }
public void PendingByteTest1() { using (MemoryStream stream = GetStream("\r\nH\ra")) using (ShellStream shellStream = new ShellStream(stream, false)) { byte[] buffer = new byte[1]; var read = shellStream.Read(buffer, 0, 1); Assert.Equal(1, read); Assert.Equal((byte)'\n', buffer[0]); read = shellStream.Read(buffer, 0, 1); Assert.Equal(1, read); Assert.Equal((byte)'H', buffer[0]); read = shellStream.Read(buffer, 0, 1); Assert.Equal(1, read); Assert.Equal((byte)'\r', buffer[0]); read = shellStream.Read(buffer, 0, 1); Assert.Equal(1, read); Assert.Equal((byte)'a', buffer[0]); } }
public Stream(SshClient ssh) { _sshClient = ssh; _sshClient.Connect(); _sshStream = _sshClient.CreateShellStream("xterm", 80, 50, 1024, 1024, 1024); while (!_sshStream.DataAvailable) { System.Threading.Thread.Sleep(200); } var line = _sshStream.Read(); _sshStream.Flush(); }
private void Listen(CancellationToken ct) { while (!ct.IsCancellationRequested) { Thread.Sleep(LISTEN_INTERVAL); if (shellStream_.DataAvailable) { string result = ""; result = shellStream_.Read(); if (result != "") { SendBytesToSubscribers(result); } } } }
public static string Expect(ShellStream shell, Regex expectedShellPrompt, string lastCommand, TimeSpan timeout) { var result = shell.Expect(expectedShellPrompt, timeout); if (result == null) { var buffer = new byte[4096]; shell.Read(buffer, 0, buffer.Length); var lastReadData = System.Text.Encoding.Default.GetString(buffer).Replace("\0", string.Empty); throw new Exception($"Timeout {timeout.TotalSeconds}s executing {lastCommand}\nExpected Regex: {expectedShellPrompt.ToString()}\nReceived text: {lastReadData}"); } result = result.Contains(lastCommand) ? result.StringAfter(lastCommand) : result; result = result.StringBeforeLastRegEx(expectedShellPrompt).Trim(); return(result); }
public override bool Execute(string workingPath, SshClient client) { int capacity = 5 * 1024 * 1024; // terminal capacity string marker = this.GenerateMarker(); string command = this._command + "; KEY_CODE=[" + marker + "]; echo \"END->${KEY_CODE}\""; //HACK ResponseExtractor extractor = new ResponseExtractor("$ " + command + "\r\n", "END->[" + marker + "]"); //HACK string result = null; using (ShellStream stream = client.CreateShellStream("solver", 237, 64, 237, 64, capacity)) { stream.WriteLine("cd \"" + workingPath + "\""); stream.WriteLine(command); byte[] buffer = new byte[256]; while (result == null) { int count = stream.Read(buffer, 0, buffer.Length); if (count > 0) { result = extractor.Analyze(buffer, count); if (result != null) { break; } } else { Thread.Sleep(100); } } stream.Close(); } this._callback.Invoke(result); return(true); }
public void TestCRLFAtStart() { using (MemoryStream stream = GetStream("\r\nHello, World!")) using (ShellStream shellStream = new ShellStream(stream, false)) using (StreamReader reader = new StreamReader(shellStream)) { Assert.Equal((int)'\n', shellStream.ReadByte()); stream.Position = 0; byte[] buffer = new byte[2]; var read = shellStream.Read(buffer, 0, 2); Assert.Equal(2, read); Assert.Equal((byte)'\n', buffer[0]); Assert.Equal((byte)'H', buffer[1]); stream.Position = 0; Assert.Equal("\nHello, World!", reader.ReadToEnd()); } }
private void recvLogSSHData(ShellStream sShell, TextBox textbox) { while (true) { try { if (sShell != null && sShell.DataAvailable) { String strData = sShell.Read(); appendTextBoxInThread(textbox, strData); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } Thread.Sleep(200); } }
private void recvCommSSHData() { while (true) { try { if (Command_sShell != null && Command_sShell.DataAvailable) { String strData = Command_sShell.Read(); appendTextBoxInThread(textBox5, strData); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } Thread.Sleep(200); } }
public void MultipleCRLFInString() { using (MemoryStream stream = GetStream("\r\n1\r\n2\r\n3\r\n4\r\n5")) using (ShellStream shellStream = new ShellStream(stream, false)) using (StreamReader reader = new StreamReader(shellStream)) { Assert.Equal((int)'\n', shellStream.ReadByte()); stream.Position = 0; byte[] buffer = new byte[100]; var read = shellStream.Read(buffer, 0, 100); var actual = Encoding.ASCII.GetString(buffer, 0, read); Assert.Equal("\n1\n2\n3\n4\n5", actual); Assert.Equal(10, read); for (int i = 10; i < buffer.Length; i++) { Assert.Equal(0, buffer[i]); } } }
private String doImdtCmd(String cmd, long timeOut = 2000000, procCmdRsltDlg procCmdRslt = null) // 100ms { if (isConnected != true) { return(null); } Action act; String tmpRead; StringBuilder result = new StringBuilder(); tmpRead = shell.Read(); shell.WriteLine(cmd); while (true) { tmpRead = shell.ReadLine(new TimeSpan(timeOut)); if (tmpRead == null) { break; } if (procCmdRslt != null) { procCmdRslt(tmpRead); } result.Append(tmpRead); act = new Action(() => { TbxTest.AppendText(tmpRead); TbxTest.AppendText("\n"); TbxTest.ScrollToEnd(); }); this.Dispatcher.Invoke(act); } if (result.Length > 0) { result.Remove(0, cmd.Length); } return(result.ToString()); }
public void ReadTest1() { 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 expected = string.Empty; // TODO: Initialize to an appropriate value string actual; actual = target.Read(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
private void button1_Click(object sender, EventArgs e) { float DeF_X = Convert.ToSingle(AxisX.Text); float DeF_Y = Convert.ToSingle(AxisY.Text); CarPosition.Refresh(); SSHInfo.Clear(); DrawingPlot(); DrawingRectangle((int)Math.Floor(DeF_X / 10), (int)Math.Floor(DeF_Y / 10)); DrawingLine((int)Math.Floor(DeF_X / 10), (int)Math.Floor(DeF_Y / 10)); previousX = CarPosition.Width / 2; previousY = CarPosition.Height / 2; RPi = new SshClient(IPBox.Text, UsernameBox.Text, PasswordBox.Text); RPi.Connect(); shell = RPi.CreateShellStream("shell", 100, 100, 100, 100, 1024); shell.Write("python3 /home/pi/Documents/fuzzy/fuzzy_script.py \n"); shell.Write(Convert.ToString(DeF_X) + "\n"); shell.Write(Convert.ToString(DeF_Y) + "\n"); shell.Flush(); bool fl = true; int counter = 0; while (fl) { if (shell != null && shell.DataAvailable) { string[] info; string data = shell.Read(); if (counter > 56) { char[] deter = { '\r', '\n' }; info = data.Split(deter); foreach (string s in info) { if (s == "") { continue; } SSHInfo.AppendText(s + "\r\n"); if (s == "DONE" || s == "Terminated") { fl = false; shell.Close(); RPi.Disconnect(); break; } if (s[0] == 'D') { SensorReading.Clear(); SensorReading.ForeColor = Color.Black; SensorReading.AppendText(s); } if (s[0] == 'P') { PWM.Clear(); PWM.AppendText(s); } if (s[0] == 'S') { Speed.Clear(); Speed.AppendText(s); } if (s[0] == 'T') { TraveledDistance.Clear(); TraveledDistance.AppendText(s); } if (s[0] == 'X') { drawRobotWay(Convert.ToSingle(s.Substring(4, s.IndexOf(':') - 4)), Convert.ToSingle(s.Substring(s.IndexOf(':') + 5))); } } } else { counter++; data = null; } } } }
private static void ClientLoop(string root, HostEntry host, List <string> commands) { bytesDownloaded = 0; string logFile = Path.Combine(root, host.Name, "log.txt"); string backupPath = Path.Combine(root, host.Name, "backup"); long backupSize = 0; long uploadSize = 0; Directory.CreateDirectory(Path.GetDirectoryName(logFile)); Regex promptRegex = new Regex(@"[$>]"); //Regex userRegex = new Regex(@"[$>]"); //Regex passwordRegex = new Regex(@"([$#>:])"); using (StreamWriter writer = File.CreateText(logFile)) using (SshClient client = Connect <SshClient>(root, host)) using (ShellStream stream = client.CreateShellStream("xterm", 255, 50, 800, 600, 1024, null)) using (SftpClient sftpClient = Connect <SftpClient>(root, host)) { if (host.IsWindows) { stream.Expect(">"); while (stream.DataAvailable) { writer.Write(stream.Read()); } } else { stream.Expect(promptRegex); while (stream.DataAvailable) { writer.Write(stream.Read()); } stream.Write("sudo -s\n"); stream.Expect("password"); WriteSecure(password, stream); stream.Expect("#"); while (stream.DataAvailable) { writer.Write(stream.Read()); } } foreach (string command in commands) { writer.WriteLine(command); if (command.StartsWith('$')) { if (command.StartsWith("$backup ", StringComparison.OrdinalIgnoreCase)) { backupSize += BackupFolder(host, backupPath, command.Substring(8), sftpClient, writer); } else if (command.StartsWith("$upload ", StringComparison.OrdinalIgnoreCase)) { uploadSize += UploadFolder(host, command.Substring(8), sftpClient, writer); } else if (command.StartsWith("$ignore ", StringComparison.OrdinalIgnoreCase)) { host.IgnoreRegex = new Regex(command.Substring(8), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } } else { Console.WriteLine("Execute command {0}", command); stream.Write(command); stream.Write("\n"); if (host.IsWindows) { stream.Expect(">"); } else { stream.Expect("#"); } while (stream.DataAvailable) { writer.Write(stream.Read()); } } } writer.Write("logout\n"); } Console.WriteLine("{0} backed up {1} ", host, BytesToString(backupSize)); Console.WriteLine("{0} uploaded {1} ", host, BytesToString(uploadSize)); }
private object SshCommsProcess(object userSpecific) { var errorOnConnect = false; try { Thread.Sleep(1000); CloudLog.Info("{0} attempting connection to {1}", GetType().Name, _address); var firstFail = false; while (!_client.IsConnected && _reconnect) { try { ConnectionStatus = SshClientStatus.AttemptingConnection; _client.Connect(); } catch { ConnectionStatus = SshClientStatus.Disconnected; if (!firstFail) { CloudLog.Warn("{0} could not connect to {1}, will retry every 30 seconds until connected", GetType().Name, _address); firstFail = true; } if (_threadWait.WaitOne(30000)) { CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name); _reconnect = false; break; } } } if (!_client.IsConnected && !_reconnect) { _client.Dispose(); _client = null; ConnectionStatus = SshClientStatus.Disconnected; return(null); } CloudLog.Notice("{0} Connected to {1}", GetType().Name, _address); _shell = _client.CreateShellStream("terminal", 80, 24, 800, 600, 100000); //_shell.DataReceived += (sender, args) => _threadWait.Set(); var data = string.Empty; try { while (_programRunning && _client.IsConnected) { while (_shell.CanRead && _shell.DataAvailable) { var bytes = new byte[100000]; var length = _shell.Read(bytes, 0, bytes.Length); #if DEBUG _stopWatch.Start(); Debug.WriteSuccess("Codec rx {0} bytes", length); #endif var incoming = Encoding.ASCII.GetString(bytes, 0, length); if (!_loggedIn && incoming.Contains("Failed to connect to system software")) { CloudLog.Error("Error received from codec at \"{0}\" on connect:\r\n{1}", _address, incoming); errorOnConnect = true; break; } #if DEBUG Debug.WriteNormal(Debug.AnsiBlue + incoming + Debug.AnsiReset); #endif data = data + incoming; if (!_loggedIn) { foreach (var line in Regex.Split(data, "\r\n|\r|\n")) { if (line == "*r Login successful") { _loggedIn = true; try { Debug.WriteSuccess("Connected!", "{0} logged into {1}", GetType().Name, _address); CloudLog.Info("{0} logged into {1}", GetType().Name, _address); _sendQueue.Enqueue(@"echo off"); var adapterType = _client.EthernetAdapter; var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(adapterType); var currentIp = CrestronEthernetHelper.GetEthernetParameter( CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapterId); var assembly = Assembly.GetExecutingAssembly().GetName(); var softwareInfo = assembly.Name + " " + assembly.Version; var model = InitialParametersClass.ControllerPromptName; _sendQueue.Enqueue(string.Format( "xCommand Peripherals Connect ID: {0} Name: \"Crestron Control System\" HardwareInfo: \"{1}\" NetworkAddress: \"{2}\" SoftwareInfo: \"{3}\" Type: ControlSystem", _heartbeatId, string.Format("Crestron {0}", model), currentIp, softwareInfo)); _sendQueue.Enqueue(@"xFeedback register /Configuration"); _sendQueue.Enqueue(@"xFeedback register /Status/SystemUnit"); _sendQueue.Enqueue(@"xFeedback register /Status/Diagnostics"); _sendQueue.Enqueue(@"xFeedback register /Status/Audio"); _sendQueue.Enqueue(@"xFeedback register /Status/Standby"); _sendQueue.Enqueue(@"xFeedback register /Status/Video"); _sendQueue.Enqueue(@"xFeedback register /Status/Cameras"); _sendQueue.Enqueue(@"xFeedback register /Status/Call"); _sendQueue.Enqueue(@"xFeedback register /Status/Conference"); _sendQueue.Enqueue(@"xFeedback register /Status/UserInterface"); _sendQueue.Enqueue(@"xFeedback register /Status/Bookings"); _sendQueue.Enqueue(@"xFeedback register /Event/OutgoingCallIndication"); _sendQueue.Enqueue(@"xFeedback register /Event/IncomingCallIndication"); _sendQueue.Enqueue(@"xFeedback register /Event/CallSuccessful"); _sendQueue.Enqueue(@"xFeedback register /Event/CallDisconnect"); _sendQueue.Enqueue(@"xFeedback register /Event/Bookings"); _sendQueue.Enqueue(@"xFeedback register /Event/CallHistory"); _sendQueue.Enqueue(@"xFeedback register /Event/UserInterface/Extensions"); _sendQueue.Enqueue(@"xFeedback register /Event/UserInterface/Presentation/ExternalSource"); _sendQueue.Enqueue(@"xStatus"); _heartBeatTimer = new CTimer( specific => _sendQueue.Enqueue( string.Format("xCommand Peripherals HeartBeat ID: {0}", _heartbeatId)), null, 60000, 60000); ConnectionStatus = SshClientStatus.Connected; } catch (Exception e) { CloudLog.Exception(e); } } } data = string.Empty; } else if (data.Contains("** end")) { var chunks = Regex.Matches(data, @"(\*(\w) [\S\s]*?)(?=\*\* end)"); data = string.Empty; if (chunks.Count > 0) { foreach (Match chunk in chunks) { var type = ReceivedDataType.Status; switch (chunk.Groups[2].Value) { case "e": type = ReceivedDataType.Event; break; case "r": type = ReceivedDataType.Response; break; case "c": type = ReceivedDataType.Configuration; break; } OnReceivedData(this, type, chunk.Groups[1].Value); } } } #if DEBUG else { Debug.WriteWarn("Waiting for more data..."); } _stopWatch.Stop(); Debug.WriteNormal("Time to process: {0} ms", _stopWatch.ElapsedMilliseconds); _stopWatch.Reset(); #endif CrestronEnvironment.AllowOtherAppsToRun(); } if (errorOnConnect) { try { _client.Disconnect(); } catch (Exception e) { CloudLog.Warn("Error closing connection to codec after error, {0}", e.Message); } break; } if (!_programRunning || !_client.IsConnected) { break; } while (_shell.CanWrite && !_sendQueue.IsEmpty) { var s = _sendQueue.Dequeue(); #if DEBUG Debug.WriteWarn("Codec Tx", s); #endif _shell.WriteLine(s); } } CloudLog.Debug("{0} left while(connected) loop", Thread.CurrentThread.Name); } catch (ObjectDisposedException e) { CloudLog.Warn("{0} ObjectDisposedException, {1}, {2}", GetType().Name, string.IsNullOrEmpty(e.ObjectName) ? "unknown" : e.ObjectName, e.Message); } catch (Exception e) { CloudLog.Exception(e, "Error handling comms process"); } _loggedIn = false; try { if (_heartBeatTimer != null && !_heartBeatTimer.Disposed) { _heartBeatTimer.Stop(); _heartBeatTimer.Dispose(); } if (_client != null) { CloudLog.Info("Disposing {0}", _client.ToString()); _client.Dispose(); _client = null; } } catch (Exception e) { CloudLog.Exception(e, "Error trying to dispose items in leaving thread"); } CloudLog.Notice("{0} Disconnected from {1}", GetType().Name, _address); } catch (Exception e) { CloudLog.Exception(e, "Error in {0}.SshCommsProcess()", GetType().Name); } ConnectionStatus = SshClientStatus.Disconnected; if (errorOnConnect) { CloudLog.Warn("Error message while connecting to {0}, Disconnected and will retry in 60 seconds", _address); if (_threadWait.WaitOne(60000)) { CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name); _reconnect = false; } } if (!_reconnect) { CloudLog.Notice("Leaving connect thread for codec at {0}", _address); return(null); } CloudLog.Notice("Waiting for 10 seconds before reconnect attempt to {0}", _address); if (_threadWait.WaitOne(10000)) { CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name); _reconnect = false; return(null); } CloudLog.Notice("Attempting reconnect to codec at {0}", _address); ConnectionStatus = SshClientStatus.AttemptingConnection; Connect(); return(null); }
/// <summary> /// Returns the possible response from the previously issues command. /// </summary> public string Read() { return(stream.Read()); }
/// <summary> /// Executes an asynchronous command /// </summary> /// <param name="csentry">The CSEntry 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> /// <param name="oldPassword">The old password, or null if performing a password set as opposed to a password change</param> /// <param name="newPassword">The new password</param> private static void ExecuteAsyncCommand(CSEntry csentry, OperationResult result, AsyncCommand command, string oldPassword, string newPassword) { 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, oldPassword, newPassword, false); TimeSpan timeout = new TimeSpan(0, 0, expectCommand.Timeout); bool expectedArrived = false; shell.Expect( timeout, new ExpectAction( expectText, (s) => { expectedArrived = true; System.Diagnostics.Debug.WriteLine(s); output += s; shell.Write(expectCommand.Command.ExpandDeclaration(csentry, oldPassword, newPassword, false) + "\n"); })); if (!expectedArrived) { output += shell.Read(); throw new UnexpectedDataException("The expected value was not found in the session in the specified timeout period"); } } else { shell.Write(sendCommand.Command.ExpandDeclaration(csentry, oldPassword, newPassword, false) + "\n"); } } if (command.ExpectSuccess != null) { if (!string.IsNullOrWhiteSpace(command.ExpectSuccess.Expect.DeclarationText)) { TimeSpan timeout = new TimeSpan(0, 0, command.ExpectSuccess.Timeout); string expectResult = shell.Expect(command.ExpectSuccess.Expect.ExpandDeclaration(csentry, oldPassword, newPassword, false), timeout); output += expectResult ?? string.Empty; if (expectResult == null) { output += shell.Read(); throw new Microsoft.MetadirectoryServices.ExtensibleExtensionException("The asynchronous command did not return the expected result"); } } } output += shell.Read(); } finally { Logger.WriteLine("Shell session log:", LogLevel.Debug); Logger.WriteLine(output, LogLevel.Debug); } }
private void recvSSHData() { string[] originArray = null; int oldLen = 0; char[] splitChar = new char[] { '\n' }; while (true) { try { if (Monitering_sShell != null && Monitering_sShell.DataAvailable) { String strData = Monitering_sShell.Read(); if (strData.LastIndexOf("$") != -1) { if (originArray == null) { originArray = strData.Split(splitChar, StringSplitOptions.RemoveEmptyEntries); } else { oldLen = originArray.Length; originArray = (string[])ResizeArray(originArray, originArray.Length + strData.Split(splitChar, StringSplitOptions.RemoveEmptyEntries).Length); strData.Split(splitChar, StringSplitOptions.RemoveEmptyEntries).CopyTo(originArray, oldLen); } if (Array.Exists(originArray, element => element.StartsWith("vmstat"))) { insertGridView(originArray); } else if (Array.Exists(originArray, element => element.StartsWith("MemTotal"))) { totalMem = Int32.Parse(originArray[1].Substring(originArray[1].IndexOf(":") + 1, originArray[1].IndexOf("kB") - (originArray[1].IndexOf(":") + 1)).Trim()); this.Invoke((MethodInvoker) delegate { label10.Text = "전체메모리 : " + totalMem.ToString("###,###,###.###"); }); } originArray = null; } else { if (originArray == null) { originArray = strData.Split(splitChar, StringSplitOptions.RemoveEmptyEntries); } else { oldLen = originArray.Length; originArray = (string[])ResizeArray(originArray, originArray.Length + strData.Split(splitChar, StringSplitOptions.RemoveEmptyEntries).Length); strData.Split(splitChar, StringSplitOptions.RemoveEmptyEntries).CopyTo(originArray, oldLen); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); originArray = null; } Thread.Sleep(200); } }
private object SshCommsProcess(object userSpecific) { try { Thread.Sleep(1000); Debug.WriteInfo(string.Format("{0} attempting connection to {1}", GetType().Name, _address)); var firstFail = false; while (!_client.IsConnected && _reconnect) { try { ConnectionStatus = ClientStatus.AttemptingConnection; _client.Connect(); } catch { ConnectionStatus = ClientStatus.Disconnected; if (!firstFail) { CloudLog.Warn("{0} could not connect to {1}, will retry every 30 seconds until connected", GetType().Name, _address); firstFail = true; } Thread.Sleep(30000); } } if (!_client.IsConnected && !_reconnect) { _client.Dispose(); _client = null; ConnectionStatus = ClientStatus.Disconnected; return(null); } CloudLog.Notice("{0} Connected to {1}", GetType().Name, _address); _shell = _client.CreateShellStream("terminal", 80, 24, 800, 600, BufferSize); var buffer = new byte[BufferSize]; var dataCount = 0; try { while (_programRunning && _client.IsConnected) { while (_shell.CanRead && _shell.DataAvailable) { var incomingData = new byte[BufferSize]; var incomingDataCount = _shell.Read(incomingData, 0, incomingData.Length); #if DEBUG _stopWatch.Start(); Debug.WriteSuccess("Tesira rx {0} bytes", incomingDataCount); //Debug.WriteNormal(Debug.AnsiBlue + // Tools.GetBytesAsReadableString(incomingData, 0, incomingDataCount, true) + // Debug.AnsiReset); #endif if (!Connected && Encoding.ASCII.GetString(incomingData, 0, incomingDataCount) .Contains("Welcome to the Tesira Text Protocol Server...")) { _requestsSent.Clear(); _requestsAwaiting.Clear(); _sendQueue.Enqueue("SESSION set verbose true"); ConnectionStatus = ClientStatus.Connected; _keepAliveTimer = new CTimer(specific => { #if DEBUG Debug.WriteInfo(GetType().Name + " Sending KeepAlive"); #endif _client.SendKeepAlive(); }, null, KeepAliveTime, KeepAliveTime); } else if (Connected) { for (var i = 0; i < incomingDataCount; i++) { buffer[dataCount] = incomingData[i]; if (buffer[dataCount] == 10) { //skip } else if (buffer[dataCount] != 13) { dataCount++; } else { if (dataCount == 0) { continue; } var line = Encoding.UTF8.GetString(buffer, 0, dataCount); dataCount = 0; #if DEBUG Debug.WriteSuccess("Tesira Rx Line", Debug.AnsiPurple + line + Debug.AnsiReset); #endif TesiraMessage message = null; if (line == "+OK") { var request = _requestsAwaiting.TryToDequeue(); if (request != null) { #if DEBUG Debug.WriteInfo("Request Response Received", request); Debug.WriteSuccess(line); #endif message = new TesiraResponse(request, null); } } else if (line.StartsWith("+OK ")) { var request = _requestsAwaiting.TryToDequeue(); if (request != null) { #if DEBUG Debug.WriteInfo("Request Response Received", request); Debug.WriteSuccess(line); #endif message = new TesiraResponse(request, line.Substring(4)); } } else if (line.StartsWith("-ERR ")) { var request = _requestsAwaiting.TryToDequeue(); if (request != null) { #if DEBUG Debug.WriteInfo("Request Response Received", request); Debug.WriteError(line); #endif message = new TesiraErrorResponse(request, line.Substring(5)); } else { Debug.WriteError("Error received and request queue returned null!"); Debug.WriteError(line); Debug.WriteError("Clearing all queues!"); _requestsSent.Clear(); _requestsAwaiting.Clear(); } } else if (line.StartsWith("! ")) { #if DEBUG Debug.WriteWarn("Notification Received"); Debug.WriteWarn(line); #endif message = new TesiraNotification(line.Substring(2)); } else if (!_requestsSent.IsEmpty) { Debug.WriteWarn("Last sent request", _requestsSent.Peek()); if (_requestsSent.Peek() == line) { _requestsAwaiting.Enqueue(_requestsSent.Dequeue()); #if DEBUG Debug.WriteNormal("Now awaiting for response for command", line); #endif } } if (message != null && ReceivedData != null && message.Type != TesiraMessageType.ErrorResponse) { if (ReceivedData == null) { continue; } try { _timeOutCount = 0; ReceivedData(this, message); } catch (Exception e) { CloudLog.Exception(e, "Error calling event handler"); } } else if (message != null && message.Type == TesiraMessageType.ErrorResponse) { _timeOutCount = 0; CloudLog.Error("Error message from Tesira: \"{0}\"", message.Message); } } } } #if DEBUG _stopWatch.Stop(); Debug.WriteNormal("Time to process: {0} ms", _stopWatch.ElapsedMilliseconds); _stopWatch.Reset(); #endif CrestronEnvironment.AllowOtherAppsToRun(); } if (!_programRunning || !_client.IsConnected) { break; } #if DEBUG //Debug.WriteNormal(Debug.AnsiBlue + // string.Format( // "Shell Can Write = {0}, _sendQueue = {1}, _requestsSent = {2}, _requestsAwaiting = {3}", // _shell.CanWrite, _sendQueue.Count, _requestsSent.Count, // _requestsAwaiting.Count) + Debug.AnsiReset); #endif if (_shell.CanWrite && !_sendQueue.IsEmpty && _requestsSent.IsEmpty && _requestsAwaiting.IsEmpty) { var s = _sendQueue.Dequeue(); if (_keepAliveTimer != null && !_keepAliveTimer.Disposed) { _keepAliveTimer.Reset(KeepAliveTime, KeepAliveTime); } #if DEBUG Debug.WriteWarn("Tesira Tx", s); #endif _timeOutCount = 0; _shell.WriteLine(s); _requestsSent.Enqueue(s); Thread.Sleep(20); } else if (!_requestsSent.IsEmpty || !_requestsAwaiting.IsEmpty) { _timeOutCount++; if (_timeOutCount > 100) { CloudLog.Warn( "Error waiting to send requests in {0}, _requestsAwaiting.Count = {1}" + "and _requestsSent.Count = {2}. Clearing queues!", GetType().Name, _requestsAwaiting.Count, _requestsSent.Count); _requestsAwaiting.Clear(); _requestsSent.Clear(); _timeOutCount = 0; } Thread.Sleep(20); } } } catch (Exception e) { CloudLog.Exception(e); } _loggedIn = false; if (_keepAliveTimer != null && !_keepAliveTimer.Disposed) { _keepAliveTimer.Stop(); _keepAliveTimer.Dispose(); _keepAliveTimer = null; } if (_client != null && _client.IsConnected) { _client.Dispose(); _client = null; } CloudLog.Notice("{0} Disconnected from {1}", GetType().Name, _address); } catch (Exception e) { CloudLog.Exception(e, "Error in {0}.SshCommsProcess()", GetType().Name); } ConnectionStatus = ClientStatus.Disconnected; if (!_reconnect || !_programRunning) { return(null); } Thread.Sleep(1000); CloudLog.Notice("Attempting reconnect to Tesira at {0}", _address); ConnectionStatus = ClientStatus.AttemptingConnection; Connect(); return(null); }
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}"); } }