public string RunCommands(List <string> commands)
        {
            if (!client.IsConnected)
            {
                InitConnection();
            }
            string oldRes = GetResultIfFreshEnough(commands);

            if (oldRes == null)
            {
                commands.Add("main");
                foreach (string c in commands)
                {
                    shellStream.WriteLine(c);
                }

                var line = shellStream.ReadLine();
                // skip lines with severity tags, detail information, unset information and basis lines (hestia1->main)
                while (line.Contains("[info]") ||
                       line.Contains("[notice]") ||
                       line.Contains("[warning]") ||
                       line.Contains("[error]") ||
                       line.Contains("[alert]") ||
                       line.Contains("For details type:") ||
                       line.Contains("Sysinfo not set.") ||
                       line.Contains("[hestia1->main]"))
                {
                    line = shellStream.ReadLine();
                }

                var res = "";

                while (line != null)
                {
                    res += line + "\r\n";
                    line = shellStream.ReadLine();
                    if (line.StartsWith("[hestia1->main]"))
                    {
                        break;
                    }
                }

                AddResult(res, commands);

                return(res);
            }
            else
            {
                return(oldRes);
            }
        }
 private void ReadLoop(TcpClient client, ShellStream stream)
 {
     using (stream)     //shell stream runner last
         using (client) //client first
         {
             var line = stream.ReadLine();
             while (line != null)
             {
                 last = DateTime.Now;
                 Shell.ParseAndExecute(shell, stream, line);
                 line = stream.ReadLine();
             }
         }
 }
示例#3
0
 /// <summary>
 /// Read the output until we see a particular line.
 /// </summary>
 /// <param name="_stream"></param>
 /// <param name="p"></param>
 private void DumpTillFind(ShellStream stream, string matchText, Action <string> ongo = null)
 {
     while (true)
     {
         var l = stream.ReadLine();
         if (l == null)
         {
             Thread.Sleep(100);
         }
         else
         {
             if (l.Contains(matchText))
             {
                 return;
             }
             else
             {
                 if (ongo != null)
                 {
                     ongo(l);
                 }
             }
         }
     }
 }
示例#4
0
        private static CommandResult RunCommand(string cmd, ShellStream stream, ref CancellationTokenSource source)
        {
            stream.WriteLine(cmd);
            StringBuilder ret = new StringBuilder();

            while (true)
            {
                try
                {
                    source.Token.ThrowIfCancellationRequested();
                    Thread.Sleep(1000);
                    string str = stream.ReadLine(TimeSpan.FromSeconds(1));
                    if (str != null)
                    {
                        if (str.Trim() != cmd)
                        {
                            ret.Append(str.TrimEnd() + "\r\n");
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                catch
                {
                    source = new CancellationTokenSource();
                    break;
                }
            }

            return($"```{ret}```");
        }
示例#5
0
        /// <summary>
        /// Read text that is sitting in the buffer. But don't do it until
        /// the computer has had a chance to dump it. There is a hardwired 10 second
        /// wait for the first text to show up.
        /// </summary>
        /// <param name="shell">The shell stream to look for text</param>
        /// <param name="msToWaitAfterText">How long to wait after text appears in the buffer before reading everything.</param>
        /// <returns></returns>
        public static async Task <string> ReadRemainingText(this ShellStream shell, int msToWaitAfterText)
        {
            var timeout = DateTime.Now + TimeSpan.FromSeconds(10);

            while (shell.Length == 0 && timeout > DateTime.Now)
            {
                Thread.Sleep(20);
            }

            if (shell.Length == 0)
            {
                throw new InvalidOperationException("Waited 10 seconds for any output from shell; nothing seen. Possible hang?");
            }

            await Task.Delay(msToWaitAfterText);

            // Sometimes two lines are sent. No idea why.
            var r = shell.ReadLine(TimeSpan.FromMilliseconds(1));

            if (r != null && r.Length > 0)
            {
                return(r);
            }
            else
            {
                return(shell.Read());
            }
        }
示例#6
0
        public string WriteLine(string command)
        {
            _sshStream.Flush();
            _sshStream.WriteLine(command);


            StringBuilder output = new StringBuilder();

            string line;

            while (!_sshStream.DataAvailable)
            {
                System.Threading.Thread.Sleep(200);
            }

//            System.Threading.Thread.Sleep(200);
            var num = 0;

            while (_sshStream.DataAvailable)
            {
                if (num > 1)
                {
                    output.Append('\n');
                }
                line = _sshStream.ReadLine();
                output.Append(line);
                num++;
            }


            return(output.ToString());
        }
示例#7
0
        private String doImdtCmd(String cmd, long timeOut = 2000000, procCmdRsltDlg procCmdRslt = null) // 100ms
        {
            if (isConnected != true)
            {
                return(null);
            }

            Action        act;
            String        tmpRead;
            StringBuilder result = new StringBuilder();

            tmpRead = shell.Read();
            shell.WriteLine(cmd);

            while (true)
            {
                tmpRead = shell.ReadLine(new TimeSpan(timeOut));

                if (tmpRead == null)
                {
                    break;
                }

                if (procCmdRslt != null)
                {
                    procCmdRslt(tmpRead);
                }
                result.Append(tmpRead);

                act = new Action(() =>
                {
                    TbxTest.AppendText(tmpRead);
                    TbxTest.AppendText("\n");
                    TbxTest.ScrollToEnd();
                });
                this.Dispatcher.Invoke(act);
            }

            if (result.Length > 0)
            {
                result.Remove(0, cmd.Length);
            }
            return(result.ToString());
        }
示例#8
0
 public string ReadLine()
 {
     if (STDMode)
     {
         return(SshShell.ReadLine());
     }
     else
     {
         throw new InvalidOperationException("STD mode only");
     }
 }
示例#9
0
        private void MiSTerPopulate_Click(object sender, RoutedEventArgs e)
        {
            SshClient _client = null;

            try
            {
                List <uint> controllers = new List <uint>();
                _client = new SshClient(txtHostname.Text, txtUsername.Text, txtPassword.Password);
                _client.Connect();
                ShellStream _data = _client.CreateShellStream("", 0, 0, 0, 0, 1000);

                Thread.Sleep(5000);

                _data.WriteLine("ls -l /dev/input/js*");
                _data.WriteLine("retrospy_end");

                while (true)
                {
                    while (!_data.DataAvailable)
                    {
                    }

                    string line = _data.ReadLine();
                    if (line.Contains("retrospy_end"))
                    {
                        break;
                    }

                    if (line.Contains("/dev/input/js"))
                    {
                        int i = line.LastIndexOf("/dev/input/js", StringComparison.Ordinal);
                        if (line.Substring(i + 13) != "*")
                        {
                            controllers.Add(uint.Parse(line.Substring(i + 13), CultureInfo.CurrentCulture));
                        }
                    }
                }

                _vm.MisterGamepad.UpdateContents(controllers);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                _ = MessageBox.Show("Couldn't connected to MiSTer to get connected controllers.");
            }
            finally
            {
                if (_client != null)
                {
                    _client.Dispose();
                }
            }
        }
示例#10
0
        private static void Main()
        {
            try
            {
                Console.WriteLine(Properties.Resources.ResourceManager.GetString("Title", CultureInfo.CurrentUICulture));

                Console.Write(Properties.Resources.ResourceManager.GetString("HostnamePrompt", CultureInfo.CurrentUICulture));
                string hostname = Console.ReadLine();
                Console.Write(Properties.Resources.ResourceManager.GetString("UsernamePrompt", CultureInfo.CurrentUICulture));
                string username = Console.ReadLine();
                Console.Write(Properties.Resources.ResourceManager.GetString("PasswordPrompt", CultureInfo.CurrentUICulture));
                string password = Console.ReadLine();

                Console.Write("");
                Console.WriteLine("\nLogging into " + (string.IsNullOrEmpty(hostname) ? "beaglebone.local" : hostname) + "...");

                using (SshClient _client = new SshClient(string.IsNullOrEmpty(hostname) ? "beaglebone.local" : hostname,
                                                         string.IsNullOrEmpty(username) ? "retrospy" : username,
                                                         string.IsNullOrEmpty(password) ? "retrospy" : password))
                {
                    _client.Connect();
                    ShellStream _data = _client.CreateShellStream("", 0, 0, 0, 0, 1000);

                    _data.WriteLine("sudo /usr/local/bin/update-usb-retrospy.sh");

                    while (true)
                    {
                        while (!_data.DataAvailable)
                        {
                        }
                        ;
                        string line = _data.ReadLine();
                        Console.WriteLine(line);
                        if (line == "Installation complete!")
                        {
                            break;
                        }
                    }
                }

                Console.WriteLine("");
                Console.WriteLine(Properties.Resources.ResourceManager.GetString("Exit", CultureInfo.CurrentUICulture));

                _ = Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nUpdater encountered an error.  Message: " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine(Properties.Resources.ResourceManager.GetString("Exit", CultureInfo.CurrentUICulture));
                _ = Console.ReadLine();
            }
        }
示例#11
0
        string read2()
        {
            StringBuilder retval = new StringBuilder();
            string        line;

            while ((line = shell_stream.ReadLine(new TimeSpan(0, 0, 1))) != null)
            {
                retval.Append(line + "\n");
            }

            return(retval.ToString());
        }
示例#12
0
 private void ReadStream(WebSocket socket, ShellStream stream)
 {
     using (var reader = new StreamReader(stream))
     {
         string s;
         while (stream != null)
         {
             s = stream.ReadLine();
             SendStringAsync(s, socket);
         }
     }
 }
        /// <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);
            }
        }
示例#14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        private string ReadStream(ShellStream stream)
        {
            var result = new StringBuilder();

            string line;

            while ((line = stream.ReadLine()) != "this-is-the-end")
            {
                result.AppendLine(line);
            }

            return(result.ToString());
        }
        private String doCommand(String cmd)
        {
            SshClient sshclient1 = new SshClient(ConnNfo);

            sshclient1.Connect();
            ShellStream mstream = sshclient1.CreateShellStream("dsaf", 80, 24, 800, 600, 4096);

            ShellStream stream = mstream;

            stream.WriteLine(cmd);
            stream.Expect(cmd);
            String results = "";
            String result  = stream.ReadLine(TimeSpan.FromMilliseconds(500));

            while (result != null)
            {
                result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
                if (result != null)
                {
                    results += "\r\n" + result;
                }
            }
            return(results);
        }
示例#16
0
        public SSHConnection(string host, string username)
        {
            this._host     = host;
            this._username = username;

            _ssh = new SshClient(_host, _username, Passwords.FetchPassword(_host, _username));
            _ssh.Connect();
            _stream = _ssh.CreateShellStream("commands", 240, 200, 132, 80, 240 * 200);

            // Next job, wait until we get a command prompt

            _stream.WriteLine("# this is a test");
            DumpTillFind(_stream, "# this is a test");
            _prompt = _stream.ReadLine();
        }
示例#17
0
        // Получение строки ответов на комманды от коммутатора
        private string GetDeviceResponse(ShellStream stream)
        {
            string line;
            string result = "";
            // Сократим начало выражения "_ea.GetEvent<MessageSentEvent>()" обозвав его "ev"
            MessageSentEvent ev = _ea.GetEvent <MessageSentEvent>();

            while ((line = stream.ReadLine(TimeSpan.FromSeconds(2))) != null)
            {
                ev.Publish(new Message {
                    ActionCode    = MessageSentEvent.StringToConsole,
                    MessageString = line
                });//Tuple.Create(MessageSentEvent.StringToConsole, line));
                result += line;
            }
            return(result);
        }
        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) { }
        }
示例#19
0
        //async Task<string> read()
        string read()
        {
            int size_buffer = 4096;

            byte[] buffer = new byte[size_buffer];

            //int cnt = stream.Read(buffer, 0, size_buffer);
            //return Encoding.UTF8.GetString(buffer, 0, cnt);

            string line;

            while ((line = stream.ReadLine(new TimeSpan(0, 0, 0, 0, 1))) != null)
            {
                Console.WriteLine(line);
            }
            //line = stream.ReadLine(new TimeSpan(0, 0, 1));

            return(line);
        }
示例#20
0
        static void ReadLine(ShellStream stream)
        {
            //读取返回流
            string line;

            while ((line = stream.ReadLine(TimeSpan.FromSeconds(2))) != null)
            {
                Console.WriteLine(line);
            }

            //等待用户输入
            string input = Console.ReadLine();

            if (input == "exit")
            {
                return;//如果输入了exit结束程序
            }
            System.Console.WriteLine("用户输入:" + input);
            //执行命令
            stream.WriteLine(input);
            //再次等待用户输入
            ReadLine(stream);
        }
示例#21
0
        void FlushCommandResultLines(ShellStream stream)
        {
            string resultString  = null;
            int    timeOut       = 120;
            var    LastReactTime = DateTime.Now;

            while ((DateTime.Now - LastReactTime).TotalSeconds < timeOut)
            {
                if (resultString != null)
                {
                    timeOut       = 10;
                    LastReactTime = DateTime.Now;

                    if (resultString.IndexOf(m_Password) < 0)
                    {
                        SF.Log.Info("{0}", resultString);
                        System.Diagnostics.Debug.Print(resultString);
                    }

                    if (resultString.IndexOf("[sudo] password for ") >= 0)
                    {
                        stream.WriteLine(m_Password);
                    }
                    else if (resultString.TrimEnd().EndsWith('$'))
                    {
                        timeOut = 1; // bash prompt
                    }
                }

                resultString = stream.ReadLine(m_WaitTime);
            }

            if (!string.IsNullOrEmpty(resultString) && (resultString.IndexOf(m_Password) < 0))
            {
                SF.Log.Info("{0}", resultString);
            }
        }
        /// <summary>
        /// Executes an asynchronous command
        /// </summary>
        /// <param name="csentry">The CSEntry to apply to this command</param>
        /// <param name="result">The result object for the current operation</param>
        /// <param name="command">The definition of the command to execute</param>
        /// <param name="oldPassword">The old password, or null if performing a password set as opposed to a password change</param>
        /// <param name="newPassword">The new password</param>
        private static void ExecuteAsyncCommand(CSEntry csentry, OperationResult result, AsyncCommand command, string oldPassword, string newPassword)
        {
            string output = string.Empty;

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

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

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

                        if (!expectedArrived)
                        {
                            output += shell.Read();
                            throw new UnexpectedDataException("The expected value was not found in the session in the specified timeout period");
                        }
                    }
                    else
                    {
                        shell.Write(sendCommand.Command.ExpandDeclaration(csentry, oldPassword, newPassword, false) + "\n");
                    }
                }

                if (command.ExpectSuccess != null)
                {
                    if (!string.IsNullOrWhiteSpace(command.ExpectSuccess.Expect.DeclarationText))
                    {
                        TimeSpan timeout      = new TimeSpan(0, 0, command.ExpectSuccess.Timeout);
                        string   expectResult = shell.Expect(command.ExpectSuccess.Expect.ExpandDeclaration(csentry, oldPassword, newPassword, false), timeout);
                        output += expectResult ?? string.Empty;

                        if (expectResult == null)
                        {
                            output += shell.Read();
                            throw new Microsoft.MetadirectoryServices.ExtensibleExtensionException("The asynchronous command did not return the expected result");
                        }
                    }
                }

                output += shell.Read();
            }
            finally
            {
                Logger.WriteLine("Shell session log:", LogLevel.Debug);
                Logger.WriteLine(output, LogLevel.Debug);
            }
        }
示例#23
0
 public static Task <string> ReadLineAsync(this ShellStream stream, TimeSpan timeout)
 {
     return(Task.Factory.StartNew(() => stream.ReadLine(timeout)));
 }
示例#24
0
 public void ReadLineTest1()
 {
     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
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     actual = target.ReadLine(timeout);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
示例#25
0
        private bool ConnectToUnix()
        {
            string result = "", s;
            string passPhrase = null;

            try
            {
                if (string.IsNullOrEmpty(Host) || string.IsNullOrEmpty(Port.ToString()) || string.IsNullOrEmpty(UserName))
                {
                    Reporter.ToLog(eLogLevel.WARN, "One of Settings of Agent is Empty ");
                    throw new Exception("One of Settings of Agent is Empty ");
                }
                if (Password == null)
                {
                    Password = "";
                }
                try
                {
                    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Host, Port);
                }
                catch (Exception)
                {
                    Reporter.ToLog(eLogLevel.WARN, "Error Connecting to Host: " + Host + " with Port: " + Port);
                    throw new Exception("Error Connecting to Host: " + Host + " with Port: " + Port);
                }

                ConnectionInfo connectionInfo = null;
                if (KeyboardIntractiveAuthentication)
                {
                    connectionInfo = KeyboardInteractiveAuthConnectionInfo();
                }
                else
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password)
                                                        );
                }


                if (!string.IsNullOrEmpty(PrivateKeyPassPhrase))
                {
                    passPhrase = PrivateKeyPassPhrase;
                }

                if (File.Exists(PrivateKey))
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password),
                                                        new PrivateKeyAuthenticationMethod(UserName,
                                                                                           new PrivateKeyFile(File.OpenRead(PrivateKey), passPhrase)
                                                                                           )
                                                        );
                }
                connectionInfo.Timeout = new TimeSpan(0, 0, SSHConnectionTimeout);
                UnixClient             = new SshClient(connectionInfo);

                Task task = Task.Factory.StartNew(() =>
                {
                    UnixClient.Connect();

                    if (UnixClient.IsConnected)
                    {
                        UnixClient.SendKeepAlive();
                        ss = UnixClient.CreateShellStream("dumb", 240, 24, 800, 600, 1024);
                    }
                });

                Stopwatch st = Stopwatch.StartNew();

                while (!task.IsCompleted && st.ElapsedMilliseconds < SSHConnectionTimeout * 1000)
                {
                    task.Wait(500);  // Give user feedback every 500ms
                    GingerCore.General.DoEvents();
                }

                if (UnixClient.IsConnected)
                {
                    mConsoleDriverWindow.ConsoleWriteText("Connected!");

                    s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    while (!String.IsNullOrEmpty(s))
                    {
                        result = result + "\n" + s;

                        s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    }
                    mConsoleDriverWindow.ConsoleWriteText(result);

                    return(true);
                }
                else
                {
                    Reporter.ToLog(eLogLevel.WARN, "Error connecting to UnixServer - " + Host);
                    throw new Exception("Error connecting to UnixServer - " + Host);
                }
            }
            catch (Exception e)
            {
                ErrorMessageFromDriver = e.Message;
                return(false);
            }
        }
示例#26
0
        static void Main(string[] args)
        {
            ProgramTools.Setup();

            var config = new Config();

            config.IP      = "0.0.0.0";
            config.Port    = 22333;
            config.Delay   = 5000;
            config.Timeout = 5000;
            config.Root    = ExecutableTools.Relative("Root");

            //args will always log to stderr because daemon flag not loaded yet
            ExecutableTools.LogArgs(new StderrWriteLine(), args, (arg) =>
            {
                ConfigTools.SetProperty(config, arg);
            });

            AssertTools.NotEmpty(config.Root, "Missing Root path");
            AssertTools.NotEmpty(config.IP, "Missing IP");
            AssertTools.Ip(config.IP, "Invalid IP");

            var pid     = Process.GetCurrentProcess().Id;
            var writers = new WriteLineCollection();

            if (!config.Daemon)
            {
                writers.Add(new StderrWriteLine());
                Logger.TRACE = new TimedWriter(writers);
            }

            Logger.Trace("Root {0}", config.Root);

            var dbpath    = Path.Combine(config.Root, "SharpDaemon.LiteDb");
            var logpath   = Path.Combine(config.Root, "SharpDaemon.Log.txt");
            var eppath    = Path.Combine(config.Root, "SharpDaemon.Endpoint.txt");
            var downloads = Path.Combine(config.Root, "Downloads");

            Directory.CreateDirectory(downloads); //creates root as well

            //acts like mutex for the workspace
            var log = new StreamWriter(logpath, true);

            writers.Add(new TextWriterWriteLine(log));

            ExecutableTools.LogArgs(new TextWriterWriteLine(log), args);

            var instance = new Instance(new Instance.Args
            {
                DbPath       = dbpath,
                RestartDelay = config.Delay,
                Downloads    = downloads,
                EndPoint     = new IPEndPoint(IPAddress.Parse(config.IP), config.Port),
            });

            Stdio.SetStatus("Listening on {0}", instance.EndPoint);

            using (var disposer = new Disposer())
            {
                //wrap to add to disposable count
                disposer.Push(new Disposable.Wrapper(log));
                disposer.Push(instance);
                disposer.Push(() => Disposing(config.Timeout));

                if (config.Daemon)
                {
                    Logger.Trace("Stdin loop...");
                    var line = Stdio.ReadLine();
                    while (line != null)
                    {
                        Logger.Trace("> {0}", line);
                        if ("exit!" == line)
                        {
                            break;
                        }
                        line = Stdio.ReadLine();
                    }
                    Logger.Trace("Stdin closed");
                }
                else
                {
                    Logger.Trace("Stdin loop...");
                    var shell  = instance.CreateShell();
                    var stream = new ShellStream(new StdoutWriteLine(), new ConsoleReadLine());
                    //disposer.Push(stream); //stdin.readline wont return even after close/dispose call
                    var line = stream.ReadLine();
                    while (line != null)
                    {
                        if ("exit!" == line)
                        {
                            break;
                        }
                        Shell.ParseAndExecute(shell, stream, line);
                        line = stream.ReadLine();
                    }
                    Logger.Trace("Stdin closed");
                }
            }

            Environment.Exit(0);
        }
示例#27
0
        private bool ConnectToUnix()
        {
            string result = "", s;
            string passPhrase = null;

            try
            {
                if (string.IsNullOrEmpty(Host) || string.IsNullOrEmpty(Port.ToString()) || string.IsNullOrEmpty(UserName))
                {
                    Reporter.ToLog(eLogLevel.INFO, "One of Settings of Agent is Empty ");
                    throw new Exception("One of Settings of Agent is Empty ");
                }
                if (Password == null)
                {
                    Password = "";
                }
                try
                {
                    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Host, Port);
                }
                catch (Exception)
                {
                    Reporter.ToLog(eLogLevel.INFO, "Error Connecting to Host: " + Host + " with Port: " + Port);
                    throw new Exception("Error Connecting to Host: " + Host + " with Port: " + Port);
                }

                var connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password)
                                                        );

                if (!string.IsNullOrEmpty(PrivateKeyPassPhrase))
                {
                    passPhrase = PrivateKeyPassPhrase;
                }

                if (File.Exists(PrivateKey))
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password),
                                                        new PrivateKeyAuthenticationMethod(UserName,
                                                                                           new PrivateKeyFile(File.OpenRead(PrivateKey), passPhrase)
                                                                                           )
                                                        );
                }

                UnixClient = new SshClient(connectionInfo);

                UnixClient.Connect();

                if (UnixClient.IsConnected)
                {
                    UnixClient.SendKeepAlive();
                    ss = UnixClient.CreateShellStream("dumb", 240, 24, 800, 600, 1024);
                    mConsoleDriverWindow.ConsoleWriteText("Connected!");

                    s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    while (!String.IsNullOrEmpty(s))
                    {
                        result = result + "\n" + s;

                        s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    }
                    mConsoleDriverWindow.ConsoleWriteText(result);

                    return(true);
                }
                else
                {
                    Reporter.ToLog(eLogLevel.INFO, "Error connecting to UnixServer - " + Host);
                    throw new Exception("Error connecting to UnixServer - " + Host);
                }
            }
            catch (Exception e)
            {
                ErrorMessageFromDriver = e.Message;
                return(false);
            }
        }