예제 #1
0
 private void InternalRunActions(IEnumerable <SshShellAction> actions)
 {
     foreach (var expectAction in actions)
     {
         _shellStream.Expect(expectAction);
     }
 }
예제 #2
0
        private static string command(string cmd, Regex terminator, Regex readyTerminator = null)
        {
            if (readyTerminator != null)
            {
                Console.Write(sshStream.Expect(readyTerminator));
            }

            sshStream.WriteLine(cmd);

            if (terminator == null)
            {
                return(null);
            }

            string output = sshStream.Expect(terminator);

            Console.Write(output);

            var s = output.IndexOf('\n');
            var e = output.LastIndexOf('\n');

            output = output.Substring(s + 1, e - s);

            return(output);
        }
예제 #3
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("Recorder", 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);
            }
        }
예제 #4
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);
        }
예제 #5
0
        private string WaitForPrompt(ShellStream stream, bool timeOut)
        {
            string result = "";

            if (timeOut)
            {
                stream.Expect(TimeSpan.FromSeconds(5), new Renci.SshNet.ExpectAction("#",
                                                                                     (output) =>
                {
                    result = output;
                }));
            }
            else
            {
                stream.Expect(new Renci.SshNet.ExpectAction("#",
                                                            (output) =>
                {
                    result = output;
                }));
            }

            if (_verbose && _console != null)
            {
                _console.Log.Write(result);
            }

            return(result);
        }
예제 #6
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);
            }
        }
예제 #7
0
        private void Button_Backup_Click(object sender, RoutedEventArgs e)
        {
            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(@"[$>]"));

            Console.WriteLine("O: " + output);

            shellStream.WriteLine($"sudo sh backup.sh {sftpClient.ConnectionInfo.Username}");
            output = shellStream.Expect(new Regex(@"([$#>:])"));
            Console.WriteLine("O: " + output);
            shellStream.WriteLine(Settings.KEY);
            output = shellStream.Expect(new Regex(@"([$#>:])"));
            Console.WriteLine("O: " + output);

            if (CheckBox_Backup_Server.IsChecked == true)
            {
                System.Windows.MessageBox.Show(Strings.BACKUP_SERVER_SUCCESS, Strings.NOTIFICATION);
            }
            if (CheckBox_Backup_Client.IsChecked == true)
            {
                try
                {
                    FolderBrowserDialog dlg    = new FolderBrowserDialog();
                    DialogResult        result = dlg.ShowDialog();

                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        string downloadPath = dlg.SelectedPath + @"\";
                        string selectedFile = Settings.BACKUP_FILENAME;

                        using (var uplfileStream = System.IO.File.Create(downloadPath + selectedFile))
                        {
                            sftpClient.DownloadFile("." + selectedFile, uplfileStream);
                        }
                    }
                }
                catch (NullReferenceException)
                {
                    System.Windows.MessageBox.Show(Strings.NO_FILE_SELECTED_DOWNLOAD, Strings.NO_FILE_SELECTED);
                }
            }

            client.Disconnect();
            Close();
        }
예제 #8
0
파일: Form1.cs 프로젝트: leovo2708/SSH
        public void ExpectSSH(string address, string login, string password, string command)
        {
            try
            {
                SshClient sshClient = new SshClient(address, 22, login, password);

                sshClient.Connect();
                IDictionary <Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>();
                termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53);

                ShellStream shellStream = sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp);


                //login
                string rep = shellStream.Expect(new Regex(@"[$]"));
                Output(rep, true);

                Thread.Sleep(1000);

                //root
                shellStream.WriteLine("su -");
                rep = shellStream.Expect(new Regex(@"[:]"));
                shellStream.WriteLine("prodan46");
                Output(rep, true);
                rep = shellStream.Expect(new Regex(@"([#])"));
                Output(rep, true);

                Thread.Sleep(100);

                //comando
                shellStream.WriteLine(command);
                rep = shellStream.Expect(new Regex(@"([#])"));
                Output(rep + Environment.NewLine + Environment.NewLine, true);

                shellStream.WriteLine("/etc/rc.d/rc.postgres status");
                rep = shellStream.Expect(new Regex(@"([#])"));
                Output(rep + Environment.NewLine + Environment.NewLine + Environment.NewLine, true);
                //if (rep.Contains(":"))
                //{

                //    shellStream.WriteLine("prodan46");
                //    rep = shellStream.Expect(new Regex(@"[$#>]"));
                //    Output(rep, true);
                //}

                sshClient.Disconnect();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                throw ex;
            }
        }
예제 #9
0
        /// <summary>
        /// Executes an asynchronous command
        /// </summary>
        /// <param name="csentry">The CSEntryChange to apply to this command</param>
        /// <param name="result">The result object for the current operation</param>
        /// <param name="command">The definition of the command to execute</param>
        private static void ExecuteAsyncCommand(CSEntryChange csentry, OperationResult result, AsyncCommand command)
        {
            string output = string.Empty;

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

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

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

                if (command.ExpectSuccess != null)
                {
                    if (!string.IsNullOrWhiteSpace(command.ExpectSuccess.Expect.DeclarationText))
                    {
                        TimeSpan timeout = new TimeSpan(0, 0, command.ExpectSuccess.Timeout);
                        if (shell.Expect(command.ExpectSuccess.Expect.ExpandDeclaration(csentry, false, false), timeout) == null)
                        {
                            throw new ExtensibleExtensionException("The asynchronous command did not return the expected result");
                        }
                    }
                }
            }
            finally
            {
                Logger.WriteLine("Shell session log:", LogLevel.Debug);
                Logger.WriteLine(output, LogLevel.Debug);
            }
        }
예제 #10
0
        private void ExperimentalSudo(SynoReportViaSSH session, string command)
        {
            try
            {
                using (SshClient sshClient = new SshClient(session.ConnectionInfo))
                {
                    sshClient.Connect();
                    IDictionary <TerminalModes, uint> termkvp = new Dictionary <TerminalModes, uint>
                    {
                        { TerminalModes.ECHO, 53 }
                    };

                    ShellStream shellStream = sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp);


                    //Get logged in
                    string rep = shellStream.Expect(new Regex(@"[$>]")); //expect user prompt
                                                                         //this.writeOutput(results, rep);
                                                                         //
                                                                         //send command
                    shellStream.WriteLine("sudo " + command);
                    rep = shellStream.Expect(new Regex(@"([$#>:])"));    //expect password or user prompt
                                                                         //this.writeOutput(results, rep);

                    //check to send password
                    if (rep.Contains(":"))
                    {
                        //send password
                        shellStream.WriteLine(session.Password);
                        rep = shellStream.Expect(new Regex(@"[$#>]"), new TimeSpan(0, 0, 10)); //expect user or root prompt
                                                                                               //this.writeOutput(results, rep);
                        if (rep == null)
                        {
                            System.Diagnostics.Debug.WriteLine("sudo action failed?");
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("{0}\r\n{1}", command, rep);
                        }
                    }

                    sshClient.Disconnect();
                }
            }//try to open connection
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
                throw;
            }
        }
        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));
            }
        }
        private string RunShellCommand(ShellStream Stream, string CommandLine, bool ExpectRootPrompt)
        {
            System.Console.Out.WriteLine("CL$ " + CommandLine);

            Stream.WriteLine(CommandLine);

            string Response = "";

            bool End = false;

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

            System.Console.Out.WriteLine(Response);

            return(Response);
        }
예제 #13
0
        public IEnumerable <string> ExecuteCommand(string command)
        {
            lock (_lock)
            {
                if (!Connected)
                {
                    Connect();
                    if (!Connected)
                    {
                        return(null);
                    }
                }

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

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

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

                    return(result);
                }
            }
        }
예제 #14
0
        public async Task SSHWriteLine(string text)
        {
            try
            {
                _shellStream.WriteLine(text);
            }
            catch (Exception e)
            {
                Logger.WriteLine(10, e.ToString());
                try
                {
                    _shellStream.Dispose();
                }
                catch
                {
                }

                if (!_client.IsConnected)
                {
                    _client.Connect();
                }
                try
                {
                    _shellStream = _client.CreateShellStream("sync - unzip", 80, 120, 640, 480, short.MaxValue);
                }
                catch
                {
                    _client.Disconnect();
                    _client.Connect();
                    _shellStream = _client.CreateShellStream("sync - unzip", 80, 120, 640, 480, short.MaxValue);
                }
                _shellStream.Expect(newLineRegex, TimeSpan.FromSeconds(SSHTimeout));
                _shellStream.WriteLine(text);
            }
        }
예제 #15
0
        public string exec(string cmdline)
        {
            shellStream.WriteLine(cmdline);
            var rep = shellStream.Expect(new Regex(@"[$#]"));

            pn(rep);
            return(rep);
        }
        private void InstallAgentAndOnboard(SshClient sshClient, ref ServerListItem server)
        {
            string installcmd = server.Architecture == ServerArchitecture.x64 ?
                                "sh /home/" + server.Username + "/" + x64Agent + " --install -w " + txtWorkspaceId.Text + " -s " + txtSharedKey.Text + "\n":
                                "sh /home/" + server.Username + "/" + x86Agent + " --install -w " + txtWorkspaceId.Text + " -s " + txtSharedKey.Text + "\n";

            IDictionary <Renci.SshNet.Common.TerminalModes, uint> termkvp = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>
            {
                { Renci.SshNet.Common.TerminalModes.ECHO, 53 }
            };
            ShellStream shell = sshClient.CreateShellStream("xterm", 800, 240, 1024, 720, 1024, termkvp);

            //ShellStream shell = sshClient.CreateShellStream("Tail", 0, 0, 0, 0, 1024);

            StreamWriter wr = new StreamWriter(shell);
            StreamReader rd = new StreamReader(shell);

            wr.AutoFlush = true;

            wr.WriteLine("su");

            string rep = shell.Expect(new Regex(@"([$#>:])"), new TimeSpan(0, 0, 3)); //expect password or user prompt

            //check to send password
            if (rep.EndsWith("Password: "******"[$#>]"), new TimeSpan(0, 0, 3));
                server.Log += rep;
                var cmd    = sshClient.CreateCommand(installcmd);
                var result = cmd.BeginExecute();
                using (var reader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true))
                {
                    while (!result.IsCompleted || !reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (line != null)
                        {
                            server.Log += line;
                        }
                    }
                }
            }
        }
예제 #17
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));
        }
예제 #18
0
        public static bool Reload(Computer cpu, string bcIP, int bcPort, string path)
        {
            if (Initialize(cpu))
            {
                string command = String.Format("./gaf.sh {0} {1} {2} &", bcIP, bcPort, path);
                shellStream.WriteLine(command);
#if (DEBUG)
                string feedback = shellStream.Expect("root", new TimeSpan(0, 0, 10));
#endif
                sshClient.Disconnect();

                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #19
0
        public static bool Start(Computer cpu, RecordFile cfile, InterceptorType type, bool rmCfile, string bcIP, int bcPort, string path)
        {
            if (Initialize(cpu))
            {
                string command = String.Format("cd dev_utilities && ./interceptor.sh -r {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} &",
                                               type.ToString(), cfile.ID, cfile.Count, cfile.Band, cfile.ARFCN, cfile.Frequency, cfile.SampleRate, cfile.Rx, rmCfile ? 1 : 0, bcIP, bcPort, path);
                shellStream.WriteLine(command);
#if (DEBUG)
                string feedback = shellStream.Expect("root", new TimeSpan(0, 0, 10));
#endif
                sshClient.Disconnect();

                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #20
0
        /// <summary>
        /// Start The Scanner
        /// </summary>
        /// <param name="cpu">CPU</param>
        /// <param name="indx">Receiver index</param>
        /// <param name="ip">Broadcast IP</param>
        /// <param name="port">Broadcast port</param>
        /// <param name="band">Band</param>
        /// <param name="gain">Gain</param>
        /// <param name="speed">Speed</param>
        /// <param name="sample_rate">Sample Rate</param>
        /// <param name="ppm">PPM</param>
        /// <returns></returns>
        public static bool Start(Computer cpu, int indx, string ip, int port, string band, int gain, int speed, int sample_rate, int ppm)
        {
            if (Initialize(cpu))
            {
                string command = String.Format("cd dev_utilities && ./scanner.sh -r {0} {1} {2} {3} {4} {5} {6} {7} &",
                                               indx, band, sample_rate, ppm, gain, speed, ip, port);
                shellStream.WriteLine(command);
#if (DEBUG)
                string feedback = shellStream.Expect("root", new TimeSpan(0, 10, 0));
#endif
                sshClient.Disconnect();

                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="password"></param>
        /// <param name="stream"></param>
        private void SwithToRoot(string password, ShellStream stream)
        {
            var prompt = stream.Expect(new Regex(@"[$>]"));

            _log.Information(prompt);

            stream.WriteLine("sudo su");
            prompt = stream.Expect(new Regex(@"([$#>:])"));
            _log.Information(prompt);

            if (!prompt.Contains(":"))
            {
                return;
            }

            stream.WriteLine(password);
            prompt = stream.Expect(new Regex(@"[$#>]"));
            _log.Information(prompt);
        }
예제 #22
0
        public static bool Start(Computer cpu, int indx, string band, int arfcn, double freq, int gain, int sr, int td, int nr, int mood, string path)
        {
            if (Initialize(cpu))
            {
                string command = String.Format("cd dev_utilities && ./receiver.sh -r {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} &",
                                               indx, band, arfcn, freq, gain, sr, td, nr, mood, path);
                shellStream.WriteLine(command);
#if (DEBUG)
                string feedback = shellStream.Expect("root", new TimeSpan(0, 0, 10));
#endif
                sshClient.Disconnect();

                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #23
0
        public bool ShellExecute(string command, TimeSpan?timespan = null)
        {
            if (!StartShellStream())
            {
                return(false);
            }
            shellStream.WriteLine(command);

            return(timespan == null || shellStream.Expect(command, timespan.Value) != null);
        }
예제 #24
0
        private bool GetExpect(ShellStream shell, string expect)
        {
            var exp = shell.Expect(expect, TimeSpan.FromSeconds(60));

            if (!string.IsNullOrEmpty(exp))
            {
                return(true);
            }
            LogTimeout(expect);
            return(false);
        }
        public void updatePath()
        {
            try
            {
                stream.WriteLine("pwd");
                stream.Expect("pwd");

                String result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
                while (result == "")
                {
                    result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
                }
                Globals.mainForm.setTerminalPathText(result);
                Globals.mainForm.setReomtePath(result);

                Globals.mainForm.clearServers();
                stream.WriteLine("ls -1ad */ 2>/dev/null");
                stream.Expect("ls -1ad */ 2>/dev/null");
                result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
                while (result != null)
                {
                    result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
                    if (result != null)
                    {
                        Globals.mainForm.addServerFolderPath(result);
                    }
                }

                Globals.mainForm.addServerFolderFile(".");
                Globals.mainForm.addServerFolderFile("..");
                stream.WriteLine("ls -p | grep -v / 2>/dev/null");
                stream.Expect("ls -p | grep -v / 2>/dev/null");
                result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
                while (result != null)
                {
                    result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
                    Globals.mainForm.addServerFolderFile(result);
                }
            }
            catch (Exception e1) { }
        }
예제 #26
0
            public string ExecuteShellCommand(string[] CommandList, string EndOfCommand)
            {
                int i = 0;

                while (i < CommandList.Length)
                {
                    WriteStream.WriteLine(CommandList[i]);
                    i++;
                }
                WriteStream.WriteLine(EndOfCommand);
                return(shell.Expect(EndOfCommand, new TimeSpan(0, 0, 10)));
            }
예제 #27
0
        private bool GetExpect(ShellStream shell, Regex expect)
        {
            var exp = shell.Expect(expect, TimeSpan.FromSeconds(60));

            if (string.IsNullOrEmpty(exp))
            {
                LogTimeout(exp);
                return(false);
            }
            _log.Information(exp);
            return(true);
        }
예제 #28
0
        public static void SwithToRoot(string password, ShellStream stream)
        {
            // Get logged in and get user prompt
            string prompt = stream.Expect(new Regex(@"[$>]"));

            //Console.WriteLine(prompt);

            // Send command and expect password or user prompt
            stream.WriteLine("su - root");
            prompt = stream.Expect(new Regex(@"([$#>:])"));
            //Console.WriteLine(prompt);

            // Check to send password
            if (prompt.Contains(":"))
            {
                // Send password
                stream.WriteLine(password);
                prompt = stream.Expect(new Regex(@"[$#>]"));
                //Console.WriteLine(prompt);
            }
        }
 private void WaitForPrompt(ShellStream stream, bool timeOut)
 {
     if (_verbose)
     {
         if (timeOut)
         {
             stream.Expect(TimeSpan.FromSeconds(5), new Renci.SshNet.ExpectAction("#",
                                                                                  (output) =>
             {
                 if (_console != null)
                 {
                     _console.Log.Write(output);
                 }
             }));
         }
         else
         {
             stream.Expect(new Renci.SshNet.ExpectAction("#",
                                                         (output) =>
             {
                 if (_console != null)
                 {
                     _console.Log.Write(output);
                 }
             }));
         }
     }
     else
     {
         if (timeOut)
         {
             stream.Expect("#", TimeSpan.FromSeconds(5));
         }
         else
         {
             stream.Expect("#");
         }
     }
 }
예제 #30
0
        public String expect(String cmd, int t)
        {
            String retval = "";

            try
            {
                stream.Write(cmd + "\r");
                stream.Flush();
                Thread.Sleep(t);
                retval = stream.Expect(reg_prompt, waitTime);
                stream.Flush();
                while (stream.DataAvailable == true)
                {
                    retval += stream.Read();
                }
                return(retval);
            }
            catch (System.Exception e)
            {
                return(retval + "\n" + "err: " + e.ToString());
            }
        }
예제 #31
0
 public void ExpectTest3()
 {
     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
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Expect(text);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
예제 #32
0
 public void ExpectTest5()
 {
     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
     TimeSpan timeout = new TimeSpan(); // TODO: Initialize to an appropriate value
     ExpectAction[] expectActions = null; // TODO: Initialize to an appropriate value
     target.Expect(timeout, expectActions);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }