// Event Handler for host key receivec.
        public ushort Connect(String Host, ushort Port, String UserName, String Password)
        {
            try
            {
                if (myClient != null && myClient.IsConnected)
                {
                    return(0);
                }
                myClient = new SshClient(Host, (int)Port, UserName, Password);
                myClient.Connect();

                // if host key override needed register eventhandler myClient.HostKeyReceived
                myClient.HostKeyReceived += new EventHandler <Crestron.SimplSharp.Ssh.Common.HostKeyEventArgs>(myClient_HostKeyReceived);

                // Create a new shellstream
                try
                {
                    myStream = myClient.CreateShellStream("terminal", 80, 24, 800, 600, 1024);
                    myStream.DataReceived += new EventHandler <Crestron.SimplSharp.Ssh.Common.ShellDataEventArgs>(myStream_DataReceived);
                }
                catch (Exception e)
                {
                    ErrorLog.Exception("Exception creating stream", e);
                }
                return(1);
            }
            catch (Exception ex)
            {
                ErrorLog.Error(String.Format("Error Connecting: {0}", ex.Message));
                return(0);
            }
        }
        private void processShellStream(ShellStream shellStream, String expectedRegexPattern, StreamWriter writer, string input, bool isOptional, ICollection <string> messages)
        {
            bool            wasExecuted = false;
            Action <string> action      = (x) => {
                if (writer != null && input != null)
                {
                    writer.WriteLine(input);
                }
                ;
                wasExecuted = true;
                messages.Clear();
            };
            var expectAction = new ExpectAction(new Regex(expectedRegexPattern, RegexOptions.IgnoreCase), action);

            shellStream.Expect(TimeSpan.FromSeconds(Timeout), expectAction);
            // Shell output is always null when the action was not executed.
            if (!(isOptional || wasExecuted))
            {
                var message = messages.LastOrDefault();
                if (messages.Count > 1)
                {
                    message = string.Format("{0} / {1}", messages.First(), messages.Last());
                }
                throw new Exception(String.Format("Error changing password. Got '{0}' from shell which didn't match the expected '{1}' regex pattern.", message, expectedRegexPattern));
            }
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        public void Init()
        {
            var appSettings = Configuration.GetSection("AppSettings").Get <AppSettings>();

            if (!appSettings.SSH.Enabled)
            {
                this.Logger.LogInformation($"SSH connection disabled in config.");
                return;
            }

            client = new SshClient(appSettings.SSH.Host, appSettings.SSH.Port, "pi", "raspberry");
            client.Connect();

            shell = client.CreateShellStream("", 80, 80, 80, 40, 1024);
            shell.DataReceived += Shell_DataReceived;
            sshThread           = new Thread(() =>
            {
                this.Logger.LogInformation($"SSH connection to {appSettings.SSH.Host}:{appSettings.SSH.Port} established.");
                while (keepRunning)
                {
                    Thread.Sleep(500);
                }
            });

            sshThread.Start();
        }
Ejemplo n.º 5
0
        static bool ReConnect(int timeout_ms = NO_TIMEOUT)
        {
            if (ServerList.selected_serverinfo_textblock == null)
            {
                return(false);
            }

            string ip       = ServerList.selected_serverinfo_textblock.serverinfo.ip;
            string id       = ServerList.selected_serverinfo_textblock.serverinfo.id;
            string password = ServerList.selected_serverinfo_textblock.serverinfo.password;
            int    port     = 22;

            try
            {
                if (!CheckConnection(sftp, ip, port, id) || !CheckConnection(ssh, ip, port, id))
                {
                    TextRange txt = new TextRange(Status.current.richTextBox_status.Document.ContentStart, Status.current.richTextBox_status.Document.ContentEnd);
                    txt.Text = "";

                    sftp = new SftpClient(ip, port, id, password);
                    if (timeout_ms != NO_TIMEOUT)
                    {
                        sftp.ConnectionInfo.Timeout = new TimeSpan(0, 0, 0, 0, timeout_ms);
                    }
                    sftp.Connect();
                    ssh = new SshClient(ip, port, id, password);
                    if (timeout_ms != NO_TIMEOUT)
                    {
                        ssh.ConnectionInfo.Timeout = new TimeSpan(0, 0, 0, 0, timeout_ms);
                    }
                    ssh.Connect();

                    if (ssh.IsConnected)
                    {
                        shell_stream        = ssh.CreateShellStream("customCommand", 80, 24, 800, 600, 4096);
                        shell_stream_reader = new StreamReader(shell_stream);
                        shell_stream_writer = new StreamWriter(shell_stream);
                    }

                    if (shell_stream_read_timer == null)
                    {
                        shell_stream_read_timer          = new DispatcherTimer();
                        shell_stream_read_timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
                        shell_stream_read_timer.Tick    += Shell_stream_read_timer_Tick;
                    }
                    //shell_stream_read_timer.Stop();
                    //shell_stream_read_timer.Start();
                    Log.PrintConsole(ip + " / " + port + " / " + id, "ReConnect" /*, test4.m_wnd.richTextBox_status*/);

                    readMessageBlocking(null);
                    return(true);
                }
            }
            catch (Exception e)
            {
                Log.PrintError(e.Message, "ReConnect", Status.current.richTextBox_status);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 6
0
        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);
        }
Ejemplo n.º 7
0
        private static bool Initialize(Computer cpu)
        {
            try
            {
                sshClient = new SshClient(cpu.IP, 22, cpu.Username, cpu.Password);
                sshClient.Connect();

                IDictionary <Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>
                {
                    { Renci.SshNet.Common.TerminalModes.ECHO, 53 }
                };

                shellStream = sshClient.CreateShellStream("Scanner", 200, 50, 800, 600, 1024, termkvp);

                // Login As Root
                string feedback = shellStream.Expect(new Regex(@"[$>]"));
                shellStream.WriteLine("sudo su");
                //expect password or user prompt
                feedback = shellStream.Expect(new Regex(@"([$#>:])"));
                if (feedback.Contains(":"))
                {
                    shellStream.WriteLine(cpu.Password);
                    //expect user or root prompt
                    feedback = shellStream.Expect(new Regex(@"[$#>]"));
                    return(true);
                }
                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 8
0
        public SavingShellStreamNotifier(TerminalControl terminal, ShellStream stream, Stream output)
        {
            this.terminal        = terminal;
            input                = stream;
            this.output          = output;
            middle               = new ProxyStream(input);
            stream.DataReceived += Stream_DataReceived;
            outputTask           = Task.Run(() =>
            {
                do
                {
                    outputWait.WaitOne();
                    if (outputQueue.IsEmpty)
                    {
                        break;
                    }

                    byte[] result;
                    while (!outputQueue.TryDequeue(out result))
                    {
                        ;
                    }

                    output.Write(result, 0, result.Length);
                } while (true);
            });
        }
Ejemplo n.º 9
0
        public StringBuilder GetCoordinates()
        {
            SshClient sshclient = new SshClient("10.130.1.1", "root", "dragino");

            if (!sshclient.IsConnected)
            {
                sshclient.Connect();
            }

            //SshClient ssh = new SshClient("10.130.1.1", "root", "dragino");
            //ssh.Connect();
            //SshCommand sc = ssh.CreateCommand("telnet localhost 6571");
            //sc.Execute();
            //Thread.Sleep(2000);
            //sc.EndExecute();

            //var result = "";
            //    while (string.IsNullOrEmpty(result))
            //    {
            //        result = ssh.RunCommand("telnet localhost 6571 > ^]").Result;
            //    }
            //    ssh.Disconnect();
            //    return result;
            //}
            ShellStream stream = sshclient.CreateShellStream("customCommand", 80, 24, 800, 600, 1024);
            var         result = SendCommand("telnet localhost 6571", stream);

            return(result);
        }
Ejemplo n.º 10
0
        private void KeepSendingWebSocketData(WebSocket webSocket, ShellStream shellStream)
        {
            new Thread(async() =>
            {
                while (!webSocket.CloseStatus.HasValue && shellStream.CanRead)
                {
                    var buffer    = new byte[BUFFERSIZE];
                    var bytesRead = await shellStream.ReadAsync(buffer, 0, BUFFERSIZE);
                    if (bytesRead > 0)
                    {
                        await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, bytesRead), WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    else
                    {
                        Thread.Sleep(100); // if nothing to send, sleep for some time before checking again
                    }
                }

                if (webSocket.CloseStatus.HasValue)
                {
                    this.logger.Trace($"Socket closed, stop getting shell response");
                }

                if (shellStream.CanRead)
                {
                    this.logger.Trace($"Can't read from shell, stop getting shell response");
                }
            }).Start();
        }
Ejemplo n.º 11
0
        public bool Connect()
        {
            this.authorition = this.Authorition as SshConnectionAuthorition;

            var authentications = new List <AuthenticationMethod>();

            if (!string.IsNullOrEmpty(this.authorition.KeyFilePath))
            {
                var privateKeyFile = new PrivateKeyFile(this.authorition.KeyFilePath, this.authorition.KeyFilePassphrase);
                authentications.Add(new PrivateKeyAuthenticationMethod(this.authorition.UserName, privateKeyFile));
            }
            authentications.Add(new PasswordAuthenticationMethod(this.authorition.UserName, this.authorition.Password));
            ConnectionInfo connectionInfo = new ConnectionInfo(this.authorition.ServerAddress, this.authorition.ServerPort, this.authorition.UserName, authentications.ToArray());

            //this.parser = new AnsiEscapeSequencesParser();

            try
            {
                this.sshClient = new SshClient(connectionInfo);
                this.sshClient.Connect();
                this.sshClient.KeepAliveInterval = TimeSpan.FromSeconds(20);
                this.shellStream = this.sshClient.CreateShellStream(this.authorition.TerminalName, this.authorition.TerminalColumns, this.authorition.TerminalRows, 0, 0, 1000);
                this.shellStream.DataReceived += this.ShellStream_DataReceived;
                this.writer = new BinaryWriter(this.shellStream, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                logger.Error("初始化SshConnection异常", ex);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 12
0
        public async Task ReadLogTests()
        {
            using (Stream stream = File.OpenRead(@"logcat.bin"))
                using (ShellStream shellStream = new ShellStream(stream, false))
                {
                    LogReader reader = new LogReader(shellStream);

                    // This stream contains 3 log entries. Read & validate the first one,
                    // read the next two ones (to be sure all data is read correctly).
                    var log = await reader.ReadEntry(CancellationToken.None);

                    Assert.IsInstanceOfType(log, typeof(AndroidLogEntry));

                    Assert.AreEqual(707, log.ProcessId);
                    Assert.AreEqual(1254, log.ThreadId);
                    Assert.AreEqual(3u, log.Id);
                    Assert.IsNotNull(log.Data);
                    Assert.AreEqual(179, log.Data.Length);
                    Assert.AreEqual(new DateTime(2015, 11, 14, 23, 38, 20, 590, DateTimeKind.Utc), log.TimeStamp);

                    var androidLog = (AndroidLogEntry)log;
                    Assert.AreEqual(Priority.Info, androidLog.Priority);
                    Assert.AreEqual("ActivityManager", androidLog.Tag);
                    Assert.AreEqual("Start proc com.google.android.gm for broadcast com.google.android.gm/.widget.GmailWidgetProvider: pid=7026 uid=10066 gids={50066, 9997, 3003, 1028, 1015} abi=x86", androidLog.Message);

                    Assert.IsNotNull(await reader.ReadEntry(CancellationToken.None));
                    Assert.IsNotNull(await reader.ReadEntry(CancellationToken.None));
                }
        }
Ejemplo n.º 13
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.º 14
0
        // Connect Button
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtHostAdress.Text) || string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPortNumber.Text))
                {
                    MessageBox.Show("Please check host, port and username field");
                }
                else
                {
                    this.sshClient = new SshClient(txtHostAdress.Text, Convert.ToInt32(txtPortNumber.Text), txtUserName.Text, txtPassword.Text);

                    this.sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
                    this.sshClient.Connect();

                    this.shellStreamSSH = this.sshClient.CreateShellStream("vt-100", 80, 60, 800, 600, 65536);
                    this.lbStatus.Text  = " Connected to " + (txtHostAdress.Text);
                }
            }
            catch (Exception exp)
            {
                this.lbStatus.Text = " Disconnected";
                MessageBox.Show("ERROR :" + exp.Message);
            }
        }
Ejemplo n.º 15
0
        private void Button_Sign_Up_Click(object sender, RoutedEventArgs e)
        {
            if (TextBox_Username.Text.Length == 0)
            {
                MessageBox.Show(Strings.LOGIN_IS_EMPTY, Strings.ERR_MSG);
            }
            else if (PasswordBox_Password.Password.Length == 0)
            {
                MessageBox.Show(Strings.PSW_IS_EMPTY, Strings.ERR_MSG);
            }
            else
            {
                SshClient client = new SshClient(Settings.HOST, 22, Settings.NAME, Settings.KEY);
                client.Connect();

                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", 80, 24, 800, 600, 1024, modes);
                var         output      = shellStream.Expect(new Regex(@"[$>]"));

                shellStream.WriteLine($"{Settings.RUN_REG_SCRIPT} {TextBox_Username.Text} {PasswordBox_Password.Password}");
                output = shellStream.Expect(new Regex(@"([$#>:])"));
                shellStream.WriteLine(Settings.KEY);
                output = shellStream.Expect(new Regex(@"([$#>:])"));

                client.Disconnect();

                MessageBox.Show(Strings.REG_SUCCESS, Strings.NOTIFICATION);
            }
        }
Ejemplo n.º 16
0
        private static void connect(string hostName, string userName, string password)
        {
            if (client != null && client.IsConnected)
            {
                return;
            }


            var connectionInfo = new KeyboardInteractiveConnectionInfo(hostName, userName);

            connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
            {
                foreach (var prompt in e.Prompts)
                {
                    prompt.Response = password;
                }
            };

            client = new SshClient(connectionInfo);
            client.Connect();

            sshStream = client.CreateShellStream("", 80, 40, 80, 40, 1024);

            shellCommand("python", null);

            using (var sr = new System.IO.StreamReader("queryJoints.py"))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    pythonCommand(line);
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Starts the monitor mode.
        /// </summary>
        /// <param name="fsmonitor">The fs monitor.</param>
        /// <param name="sshClient">The SSH client.</param>
        /// <param name="sftpClient">The SFTP client.</param>
        /// <param name="shellStream">The shell stream.</param>
        /// <param name="verbOptions">The verb options.</param>
        private static void StartMonitorMode(
            FileSystemMonitor fsmonitor,
            SshClient sshClient,
            SftpClient sftpClient,
            ShellStream shellStream,
            MonitorVerbOptions verbOptions)
        {
            fsmonitor.FileSystemEntryChanged += (s, e) =>
            {
                // Detect changes to the monitor file by ignoring deletions and checking file paths.
                if (e.ChangeType != FileSystemEntryChangeType.FileAdded &&
                    e.ChangeType != FileSystemEntryChangeType.FileModified)
                {
                    return;
                }

                // If the change was not in the monitor file, then ignore it
                if (e.Path.ToLowerInvariant().Equals(verbOptions.MonitorFile.ToLowerInvariant()) == false)
                {
                    return;
                }

                // Create a new deployment once
                CreateNewDeployment(sshClient, sftpClient, shellStream, verbOptions);
            };

            "File System Monitor is now running.".WriteLine();
            "Writing a new monitor file will trigger a new deployment.".WriteLine();
            "Press H for help!".WriteLine();
            "Ground Control to Major Tom: Have a nice trip in space!.".WriteLine(ConsoleColor.DarkCyan);
        }
Ejemplo n.º 18
0
 public WebSMiddleware(RequestDelegate next, AllRepositories allRep)
 {
     _allRep = allRep;
     _next   = next;
     _client = null;
     _stream = null;
 }
Ejemplo n.º 19
0
        private void Tomcat_LogStart()
        {
            if (listBox1.SelectedItem.ToString() == "All")
            {
                for (int t = 0; t < listBox1.Items.Count; t++)
                {
                    if (!listBox1.Items[t].ToString().Equals("All"))
                    {
                        switch (t)
                        {
                        case 1:
                            cSSH_TomCat_Log1 = Connect_SSH(textBox1.Text, Convert.ToInt32(textBox2.Text), textBox3.Text, textBox4.Text);

                            Tomcat_Log_sShell1 = cSSH_TomCat_Log1.CreateShellStream("vt100", 80, 60, 800, 600, 65536);

                            if (cSSH_TomCat_Log1.IsConnected)
                            {
                                Tomcat_Log_thread1 = new Thread(() => recvLogSSHData(Tomcat_Log_sShell1, textBox10));

                                Tomcat_Log_thread1.IsBackground = true;
                                Tomcat_Log_thread1.Start();
                            }
                            break;

                        case 2:
                            cSSH_TomCat_Log2 = Connect_SSH(textBox1.Text, Convert.ToInt32(textBox2.Text), textBox3.Text, textBox4.Text);

                            Tomcat_Log_sShell2 = cSSH_TomCat_Log2.CreateShellStream("vt100", 80, 60, 800, 600, 65536);

                            if (cSSH_TomCat_Log2.IsConnected)
                            {
                                Tomcat_Log_thread2 = new Thread(() => recvLogSSHData(Tomcat_Log_sShell2, textBox9));

                                Tomcat_Log_thread2.IsBackground = true;
                                Tomcat_Log_thread2.Start();
                            }
                            break;

                        case 3:
                            cSSH_TomCat_Log3 = Connect_SSH(textBox1.Text, Convert.ToInt32(textBox2.Text), textBox3.Text, textBox4.Text);

                            Tomcat_Log_sShell3 = cSSH_TomCat_Log3.CreateShellStream("vt100", 80, 60, 800, 600, 65536);

                            if (cSSH_TomCat_Log3.IsConnected)
                            {
                                Tomcat_Log_thread3 = new Thread(() => recvLogSSHData(Tomcat_Log_sShell3, textBox11));

                                Tomcat_Log_thread3.IsBackground = true;
                                Tomcat_Log_thread3.Start();
                            }
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
    private void CreateClient(string id)
    {
        var server = _allRep.DeploymentServerRep.GetById(id);

        _client = new SshClient(server.Address, server.Port, server.Username, server.Password);
        _client.Connect();
        _stream = _client.CreateShellStream("shell", 80, 24, 800, 600, 1024);
    }
Ejemplo n.º 21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="cmd"></param>
 /// <param name="stream"></param>
 private void WriteStream(string cmd, ShellStream stream)
 {
     stream.WriteLine(cmd + "; echo this-is-the-end");
     while (stream.Length == 0)
     {
         Thread.Sleep(500);
     }
 }
Ejemplo n.º 22
0
 /// <summary>
 /// This function writes the command to the ShellStream.
 /// Source of code: https://newbedev.com/how-to-run-commands-on-ssh-server-in-c
 /// </summary>
 /// <param name="cmd"></param>
 /// <param name="writer"></param>
 /// <param name="stream"></param>
 private static void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
 {
     writer.WriteLine(cmd);
     while (stream.Length == 0)
     {
         Thread.Sleep(500);
     }
 }
Ejemplo n.º 23
0
 private void Dispose()
 {
     Command.Dispose();
     FoundConsoleEnd = null;
     Writer?.Close(); Writer?.Dispose(); Writer = StreamWriter.Null;
     Terminal?.Close(); Terminal?.Dispose();
     Terminal = null;
 }
Ejemplo n.º 24
0
 private static void WriteRequest(string command, StreamWriter writer, ShellStream stream)
 {
     writer.WriteLine(command);
     while (stream.Length == 0)
     {
         Thread.Sleep(250);
     }
 }
Ejemplo n.º 25
0
        public void Connect()
        {
            sshClient.Connect();
            ss = sshClient.CreateShellStream(Host, 10, 10, 10, 10, 1024);

            thr = new Thread(thrRead);
            thr.Start();
        }
Ejemplo n.º 26
0
 private void UnpartitionDisks(ShellStream stream, List <Disk> disks)
 {
     disks.ForEach(foreignDisk =>
     {
         ExecuteAndPrintOutput(stream, $"disk unpartition {foreignDisk.NodeName}");
         ExecuteAndPrintOutput(stream, "y");
     });
 }
Ejemplo n.º 27
0
        static string SendShellCommand(string cmd, ShellStream stream)
        {
            var    reader = new StreamReader(stream);
            var    writer = new StreamWriter(stream);
            string text;
            bool   ok;

            ok = false;
            while (!ok)
            {
                text = reader.ReadLine();

                if (text != null)
                {
                    // Console.WriteLine("*!* {0}", text);

                    if (text.Contains("OK"))
                    {
                        ok = true;
                    }
                }
                else
                {
                    Thread.Sleep(100);
                }
            }

            var result = new StringBuilder();

            writer.WriteLine(cmd);
            writer.Flush();

            ok = false;
            while (!ok)
            {
                text = reader.ReadLine();

                if (text != null)
                {
                    // Console.WriteLine("*!* {0}", text);

                    if (text.Contains("OK"))
                    {
                        ok = true;
                    }
                    else
                    {
                        result.AppendLine(text.Trim());
                    }
                }
                else
                {
                    Thread.Sleep(100);
                }
            }

            return(result.ToString());
        }
Ejemplo n.º 28
0
        static void _main()
        {
            BlackCore.basic.cParams args = bcore.app.args;

            client = new System.Net.Sockets.TcpClient();



            int wavInDevices = WaveIn.DeviceCount;
            int selWav       = 0;

            for (int wavDevice = 0; wavDevice < wavInDevices; wavDevice++)
            {
                WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(wavDevice);
                Console.WriteLine("Device {0}: {1}, {2} channels", wavDevice, deviceInfo.ProductName, deviceInfo.Channels);
            }

            Console.Write("Select device: ");
            selWav = int.Parse(Console.ReadLine());
            Console.WriteLine("Selected device is " + selWav.ToString());


            sshClient = new SshClient(args["host"], args["user"], args["pass"]);
            sshClient.Connect();

            if (sshClient.IsConnected)
            {
                shell = sshClient.CreateShellStream("xterm", 50, 50, 640, 480, 17640);
                Console.WriteLine("Open listening socket...");
                shell.WriteLine("nc -l " + args["port"] + "|pacat --playback");
                System.Threading.Thread.Sleep(2000);

                Console.WriteLine("Try to connect...");
                client.Connect(args["host"], int.Parse(args["port"]));
                if (!client.Connected)
                {
                    return;
                }
                upStream = client.GetStream();

                //====================

                WaveInEvent wavInStream = new WaveInEvent();
                wavInStream.DataAvailable += new EventHandler <WaveInEventArgs>(wavInStream_DataAvailable);
                wavInStream.DeviceNumber   = selWav;
                wavInStream.WaveFormat     = new WaveFormat(44100, 16, 2);
                wavInStream.StartRecording();
                Console.WriteLine("Working.....");


                Console.ReadKey();
                sshClient.Disconnect();
                client.Close();
                wavInStream.StopRecording();
                wavInStream.Dispose();
                wavInStream = null;
            }
        }
Ejemplo n.º 29
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();
            }
        }
Ejemplo n.º 30
0
        public void Connect(ShellStream stream, ConnectionSettings settings)
        {
            var notifier = new ShellStreamNotifier(terminalControl, stream);

            viewModel.Connect(notifier, settings);
            notifier.Start();

            terminalControl.Terminal = viewModel.Terminal;
        }
Ejemplo n.º 31
0
 public void BeginExpectTest1()
 {
     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
     ExpectAction[] expectActions = null; // TODO: Initialize to an appropriate value
     IAsyncResult expected = null; // TODO: Initialize to an appropriate value
     IAsyncResult actual;
     actual = target.BeginExpect(expectActions);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Ejemplo n.º 32
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.º 33
0
 public void SeekTest()
 {
     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
     long offset = 0; // TODO: Initialize to an appropriate value
     SeekOrigin origin = new SeekOrigin(); // TODO: Initialize to an appropriate value
     long expected = 0; // TODO: Initialize to an appropriate value
     long actual;
     actual = target.Seek(offset, origin);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Ejemplo n.º 34
0
 public void ReadTest()
 {
     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
     byte[] buffer = null; // TODO: Initialize to an appropriate value
     int offset = 0; // TODO: Initialize to an appropriate value
     int count = 0; // TODO: Initialize to an appropriate value
     int expected = 0; // TODO: Initialize to an appropriate value
     int actual;
     actual = target.Read(buffer, offset, count);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Ejemplo n.º 35
0
 public void LengthTest()
 {
     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
     long actual;
     actual = target.Length;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Ejemplo n.º 36
0
 public void ExpectTest2()
 {
     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
     TimeSpan timeout = new TimeSpan(); // TODO: Initialize to an appropriate value
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Expect(text, timeout);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }