Beispiel #1
0
 public void CloseStream()
 {
     if (STDMode)
     {
         SshShell.Close();
     }
     else
     {
         throw new InvalidOperationException("STD mode only");
     }
 }
Beispiel #2
0
        public virtual string CloseConsole(UserGameParam param, string closeCommand = "")
        {
            var run = $"^b d";

            if (Terminal == null || Writer == StreamWriter.Null)
            {
                return("");
            }
            Writer?.WriteLine(run);
            FoundConsoleEnd        = null;
            Terminal.DataReceived += Terminal_DataReceived;
            Writer?.Close(); Writer?.Dispose(); Writer = StreamWriter.Null;
            Terminal?.Close(); Terminal?.Dispose();
            return(CollectResiveString);
        }
        private void Cleanup()
        {
            if (sshClient != null)
            {
                if (sshClient.IsConnected)
                {
                    sshClient.Disconnect();
                }
                sshClient.Dispose();
            }

            if (currentShellStream != null)
            {
                currentShellStream.Close();
                currentShellStream.Dispose();
            }

            var disposableObjects = _objectContainer.Where(o => o is IDisposable);

            foreach (var obj in disposableObjects)
            {
                if (obj is IDisposable dispObject)
                {
                    dispObject.Dispose();
                }
            }
            _objectContainer.Clear();
        }
        public EthernetSwitch Send(EthernetSwitch ethernetDevice, Dictionary <string, string> SettingsDict)
        {
            _sDict = SettingsDict;

            ShellStream stream = _sshClient.CreateShellStream("", 0, 0, 0, 0, 0);

            stream.WriteLine("sh system id");

            GetIDoverSSH(GetDeviceResponse(stream), ethernetDevice);

            stream.WriteLine("en");
            stream.WriteLine(_sDict["NewAdminPassword"]);
            stream.WriteLine("conf t");
            stream.WriteLine("no ip telnet server");
            stream.WriteLine("exit");
            stream.WriteLine("wr mem");
#if DEBUG
            stream.WriteLine("N");
#endif
#if !DEBUG
            stream.WriteLine("Y");
#endif
            GetDeviceResponse(stream);

            stream.Close();

            return(ethernetDevice);
        }
 public void Dispose()
 {
     _shell?.Dispose();
     _shell?.Close();
     _sshClient?.Disconnect();
     _sshClient?.Dispose();
 }
Beispiel #6
0
 public void Disconnect()
 {
     System.Diagnostics.Debug.WriteLineIf(DEBUG, "ssh: disconnecting ....");
     _stream.Close();
     _stream.Dispose();
     _client.Disconnect();
     _client = null;
 }
Beispiel #7
0
        private String tcExeFileName;   // TensileConv可执行文件名称

        // SSH连接或断开
        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            IpAddr   = TbxIpAddr.Text;
            Username = TbxUsername.Text;
            Password = TbxPassword.Text;

            ssh = new SshClient(IpAddr, Username, Password);

            if (isConnected == false)
            {
                // 连接
                try
                {
                    ssh.Connect();
                    shell = ssh.CreateShellStream("xtem", 180, 24, 800, 600, 1024);
                    BtnConnect.Content   = "断开";
                    btnTensile.IsEnabled = true;
                    isConnected          = true;
                }
                catch (Exception ex)
                {
                    isConnected        = false;
                    BtnConnect.Content = "连接";
                    TbxTest.Text       = "连接SSH失败,原因:{0}" + ex.Message;
                }

                if (isConnected == false)
                {
                    return;
                }

                if (Username == "root")
                {
                    doImdtCmd("cd /home");
                }
                doImdtCmd("mkdir " + remoteFolder);                                      // 建立临时目录
                doImdtCmd("cd " + remoteFolder);                                         // 进入临时目录
                remoteWorkPath = doImdtCmd("pwd");                                       // 获得临时目录全路径
                uploadFile("./" + tcExeFileName);                                        // 上传TensileConv.out文件
                sudoImdtCmd("chmod +x ./" + tcExeFileName);                              // 变为可执行文件
                Thread.Sleep(200);
                doImdtCmd("./TensileConv.out --evinfo 1", 5000000, procEnvironmentInfo); // 获得硬件及运行时信息
                                                                                         //  doWaitCmd("./TensileConv.out --evinfo 1", procEnvironmentInfo);      // 获得硬件及运行时信息
            }
            else // 断开连接
            {
                doImdtCmd("cd ..");
                doImdtCmd("rm -rf " + remoteFolder);

                shell.Close();
                ssh.Disconnect();
                Thread.Sleep(100);

                myInitialize();
                initControls();
            }
        }
Beispiel #8
0
        public override TaskStatus Run()
        {
            Info("Running SSH command...");

            var         success = true;
            ShellStream stream  = null;

            try
            {
                var       connectionInfo = new ConnectionInfo(Host, Port, Username, new PasswordAuthenticationMethod(Username, Password));
                SshClient sshclient      = new SshClient(connectionInfo);
                sshclient.Connect();
                var modes = new Dictionary <TerminalModes, uint> {
                    { TerminalModes.ECHO, 53 }
                };
                stream = sshclient.CreateShellStream("xterm", 80, 24, 800, 600, 4096, modes);
                var result = stream.Expect(Prompt, ExpectTimeout);

                if (result == null)
                {
                    Error($"Timeout {Timeout} seconds reached while connecting.");
                    return(new TaskStatus(WorkflowStatus.Error));
                }

                foreach (var line in result.GetLines())
                {
                    Info(line);
                }

                SendCommand(stream, Cmd);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Error while running SSH command: {0}\n", e.Message);
                success = false;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            var status = WorkflowStatus.Success;

            if (!success)
            {
                status = WorkflowStatus.Error;
            }

            Info("Task finished.");
            return(new TaskStatus(status));
        }
Beispiel #9
0
 /// <summary>
 /// Kills the stream
 /// </summary>
 void KillStream()
 {
     if (TheStream != null)
     {
         TheStream.DataReceived -= Stream_DataReceived;
         TheStream.Close();
         TheStream.Dispose();
         TheStream = null;
     }
 }
Beispiel #10
0
        /// <summary>
        /// Stop log capture.
        /// </summary>
        /// <returns></returns>
        public string Stop()
        {
            Thread.Sleep(TimeSpan.FromSeconds(Log.StopDelay));
            _shellStream.Close();

            var output = _client.RunCommand($"cat {_tempFile}").Result;

            _client.RunCommand($"rm {_tempFile}");
            _client.Disconnect();

            return(output);
        }
Beispiel #11
0
        private string ExecuteUDCommand(string PreCommand, string Command)
        {
            SshClient      UnixClient;
            string         cmdResult = string.Empty;
            int            iPort;
            ConnectionInfo connectionInfo;

            if (int.TryParse(Port.ValueForDriver, out iPort))
            {
                connectionInfo = new ConnectionInfo(Host.ValueForDriver, iPort, UserName.ValueForDriver,
                                                    new PasswordAuthenticationMethod(UserName.ValueForDriver, Password.ValueForDriver));
            }

            else
            {
                connectionInfo = new ConnectionInfo(Host.ValueForDriver, UserName.ValueForDriver,
                                                    new PasswordAuthenticationMethod(UserName.ValueForDriver, Password.ValueForDriver));
            }

            UnixClient = new SshClient(connectionInfo);
            UnixClient.Connect();
            if (UnixClient.IsConnected)
            {
                ExInfo += "Connected to: " + Host.ValueForDriver;
            }
            else
            {
                ExInfo += "Cannot connect to: " + Host.ValueForDriver;
                Error  += "Cannot connect to: " + Host.ValueForDriver;
                return(null);
            }
            using (ShellStream shell = UnixClient.CreateShellStream("tmp", 80, 24, 800, 600, 1024))
            {
                //StreamWriter writer = new StreamWriter(shell);

                if (PreCommand != "")
                {
                    ExInfo += ", Sending PreCommand: " + PreCommand;
                    foreach (string sCmd in PreCommand.Split(';'))
                    {
                        cmdResult += ExecuteCommandUsingShellStream(shell, sCmd);
                    }
                    ExInfo += ", PreCommandResult: " + cmdResult;
                }
                cmdResult = ExecuteCommandUsingShellStream(shell, Command);
                ExInfo   += ", Result: " + cmdResult;
                shell.Close();
            }
            UnixClient.Disconnect();

            return(cmdResult);
        }
Beispiel #12
0
        public void Dispose()
        {
            _shellStream?.Close();
            _shellStream = null;

            _client?.Dispose();
            _client = null;

            _sftp?.Dispose();
            _sftp = null;

            _fsw?.Dispose();
            _fsw = null;
        }
Beispiel #13
0
        public override Why DisConnect()
        {
            try
            {
                sshShellStream.Close();
                sshShellStream.TryDispose();
                client.Disconnect();
                //client.TryDispose();
            }
            catch (ObjectDisposedException ex)
            {
            }

            State = DeviceState.NotConnected;
            return(true);
        }
Beispiel #14
0
        private void Disconnect()
        {
            lock (_lock)
            {
                if (Connected)
                {
                    _shellStream?.Close();
                    _shellStream = null;

                    _sshClient?.Disconnect();
                    _sshClient = null;
                }

                _connectionValid = false;
            }
        }
Beispiel #15
0
 public void Stop()
 {
     if (_data != null)
     {
         try { // If the device has been unplugged, Close will throw an IOException.  This is fine, we'll just keep cleaning up.
             _data.Close();
         }
         catch (IOException) {}
         _data = null;
         _client.Disconnect();
     }
     if (_timer != null)
     {
         _timer.Stop();
         _timer = null;
     }
 }
Beispiel #16
0
        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);
        }
Beispiel #17
0
        private void Connect()
        {
            lock (_lock)
            {
                if (Connected)
                {
                    Disconnect();
                }

                try
                {
                    using (var authMethod = new PasswordAuthenticationMethod(_username, _password))
                    {
                        var connectionInfo = new ConnectionInfo(_host, _port, _username, authMethod);

                        _sshClient = new SshClient(connectionInfo);
                        _sshClient.Connect();
                        _shellStream = _sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024);

                        // This will pull the initial login prompt off the stream
                        _shellStream.Expect(new Regex(_terminalPrompt));
                    }

                    _connectionValid = true;
                }
                catch (Exception)
                {
                    _connectionValid = false;

                    _shellStream?.Close();
                    _shellStream = null;

                    _sshClient?.Disconnect();
                    _sshClient = null;

                    throw;
                }
            }
        }
Beispiel #18
0
        private void AlldisConnection()
        {
            try
            {
                aTimer.Stop();

                Mon_thread1.Abort();
                Tomcat_Log_thread1.Abort();
                Tomcat_Log_thread2.Abort();
                Tomcat_Log_thread3.Abort();

                Command_sShell.Close();
                Monitering_sShell.Close();
                Tomcat_Log_sShell1.Close();
                Tomcat_Log_sShell2.Close();
                Tomcat_Log_sShell3.Close();

                cSSH_Monitering.Disconnect();
                cSSH_TomCat_Log1.Disconnect();
                cSSH_TomCat_Log2.Disconnect();
                cSSH_TomCat_Log3.Disconnect();

                textBox5.Text  = "";
                textBox9.Text  = "";
                textBox10.Text = "";
                textBox11.Text = "";

                chart1 = null;
                chart2 = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Beispiel #19
0
 public void Close()
 {
     stream.Close();
 }
        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;
                    }
                }
            }
        }
        public SocketResponse Disconnect()
        {
            string totalResponse = "";

            switch (EquipmentConnectionSetting.ConnectionType)
            {
            case ConnectionType.TcpIp:

                //Add logout sequence here
                if (EquipmentConnectionSetting.LogoutSequences != null && EquipmentConnectionSetting.LogoutSequences.Any())
                {
                    foreach (var sequence in EquipmentConnectionSetting.LogoutSequences.OrderBy(p => p.SequenceNumber))
                    {
                        if (!string.IsNullOrEmpty(sequence.ExpectedResponse))
                        {
                            var response = SendCommandAndWaitForResponse(sequence.Command.Unescape(), new List <string> {
                                sequence.ExpectedResponse
                            }, new TimeSpan(0, 0, 0, sequence.Timeout));
                            totalResponse += response + Environment.NewLine;
                            if (response.TimeoutOccurred)
                            {
                                throw new Exception("Unable to logout." + totalResponse);
                            }
                        }
                        else
                        {
                            SendCommand(sequence.Command);
                        }
                    }
                }

                _socketClient.Close();
                break;

            case ConnectionType.Ssh:

                //Add logout sequence here
                if (EquipmentConnectionSetting.LogoutSequences != null && EquipmentConnectionSetting.LogoutSequences.Any())
                {
                    foreach (var sequence in EquipmentConnectionSetting.LogoutSequences.OrderBy(p => p.SequenceNumber))
                    {
                        if (!string.IsNullOrEmpty(sequence.ExpectedResponse))
                        {
                            var response = SendCommandAndWaitForResponse(sequence.Command.Unescape(), new List <string> {
                                sequence.ExpectedResponse
                            }, new TimeSpan(0, 0, 0, sequence.Timeout));
                            totalResponse += response.Data + Environment.NewLine;
                            if (response.TimeoutOccurred)
                            {
                                throw new Exception("Unable to logout." + totalResponse);
                            }
                        }
                        else
                        {
                            SendCommand(sequence.Command);
                        }
                    }
                }

                _shellStream.Close();
                _sshClient.Disconnect();
                //_sshClient.Dispose();
                break;

            case ConnectionType.Telnet:

                //Add logout sequence here
                if (EquipmentConnectionSetting.LogoutSequences != null && EquipmentConnectionSetting.LogoutSequences.Any())
                {
                    foreach (var sequence in EquipmentConnectionSetting.LogoutSequences.OrderBy(p => p.SequenceNumber))
                    {
                        if (!string.IsNullOrEmpty(sequence.ExpectedResponse))
                        {
                            var response = SendCommandAndWaitForResponse(sequence.Command.Unescape(), new List <string> {
                                sequence.ExpectedResponse
                            }, new TimeSpan(0, 0, 0, sequence.Timeout));
                            totalResponse += response.Data + Environment.NewLine;
                            if (response.TimeoutOccurred)
                            {
                                throw new Exception("Unable to logout." + totalResponse);
                            }
                        }
                        else
                        {
                            SendCommand(sequence.Command);
                        }
                    }
                }

                _socketClient.Close();
                break;

            default:
                throw new NotImplementedException();
            }

            return(new SocketResponse
            {
                Data = totalResponse,
                TimeoutOccurred = false
            });
        }
Beispiel #22
0
 public void Stop()
 {
     stopped = true;
     stream.Close();
     received.Release();
 }
Beispiel #23
0
 public void Close()
 {
     cts_.Cancel();
     shellStream_.Close();
 }
Beispiel #24
0
 private void DisconnectButton_Click(object sender, RoutedEventArgs e)
 {
     m_Serial.Close();
     m_SSHStream.Close();
     WriteStatusLine("Disconnected.");
 }