/// <summary>
        /// SSHs the alive.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="uid">The uid.</param>
        /// <param name="pwd">The password.</param>
        /// <param name="errOut">The error out.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <example>
        /// bool value = SSHCommand.SSHAlive("TestMachine", "root", "toor", out errOut);
        /// </example>
        public static bool SSHAlive(string host, string uid, string pwd, out string errOut)
        {
            bool bAns = false;

            errOut = @"";
            try
            {
                var connectionInfo = new ConnectionInfo(host,
                                                        uid,
                                                        new PasswordAuthenticationMethod(uid, pwd),
                                                        new PrivateKeyAuthenticationMethod(General.RsaKey));
                using (var client = new SshClient(connectionInfo))
                {
                    var input = new PipeStream();
                    client.Connect();
                    var shell = client.CreateShell(input, Console.OpenStandardOutput(), new MemoryStream());
                    shell.Start();
                    client.Disconnect();
                }
                bAns = true;
            }
            catch (Exception e)
            {
                errOut = ErrorMessage("SSHAlive", e);
            }
            return(bAns);
        }
        /// <summary>
        /// Runs the command.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="uid">The uid.</param>
        /// <param name="pwd">The password.</param>
        /// <param name="cmd">The command.</param>
        /// <param name="errOut">The error out.</param>
        /// <returns>System.String.</returns>
        /// <example>
        /// string value = SSHCommand.RunCommand("TestMachine", "root", "toor","cd /var/log/; ls -l", out errOut); <br/>
        /// <br/>
        /// <br/>
        /// <b>Results:</b><br/>
        /// -rw-r--r-- 1 root              root        106931 Jul 24 15:04 alternatives.log<br/>
        /// drwxr-x--- 2 root adm           4096 Feb 20  2019 apache2<br/>
        ///drwxr-xr-x 2 root root          4096 Jul 24 15:00 apt<br/>
        ///-rw-r----- 1 root adm          74601 Oct 30 08:01 auth.log<br/>
        ///-rw------- 1 root root         49237 Oct 30 07:32 boot.log<br/>
        ///-rw-r--r-- 1 root root             0 Jan 30  2019 bootstrap.log<br/>
        ///-rw-rw---- 1 root utmp           768 Oct 30 07:45 btmp<br/>
        ///drwxr-xr-x 2 root root          4096 Apr 19  2018 chkrootkit<br/>
        ///-rw-r----- 1 root adm        1301653 Oct 30 08:01 daemon.log<br/>
        ///-rw-r----- 1 root adm         462421 Oct 30 07:48 debug<br/>
        ///-rw-r--r-- 1 root root       1124294 Jul 24 15:05 dpkg.log<br/>
        ///drwxr-xr-x 2 dradis dradis        4096 Feb 20  2019 dradis<br/>
        ///drwxr-s--- 2 Debian-exim adm           4096 Feb 20  2019 exim4<br/>
        ///-rw-r--r-- 1 root root          4352 Jul 24 15:04 faillog<br/>
        ///-rw-r--r-- 1 root root          6155 Jul 24 15:05 fontconfig.log<br/>
        ///drwx--x--x 2 root Debian-gdm    4096 Sep 26  2018 gdm3<br/>
        ///drwx------ 3 inetsim inetsim       4096 Feb 20  2019 inetsim<br/>
        ///drwxr-xr-x 3 root root          4096 Feb 20  2019 installer<br/>
        ///-rw-r----- 1 root adm        1193710 Oct 30 07:43 kern.log<br/>
        ///-rw-rw-r-- 1 root utmp         39712 Oct 30 08:01 lastlog<br/>
        ///-rw-r--r-- 1 root root          1944 Oct 30 07:32 macchanger.log<br/>
        ///-rw-r----- 1 root adm        6531487 Oct 30 07:59 messages<br/>
        /// </example>
        public static string RunCommand(string host, string uid, string pwd, string cmd, out string errOut)
        {
            string sAns = @"";

            errOut = @"";
            try
            {
                ConnectionInfo connectionInfo = new ConnectionInfo(host, uid, new PasswordAuthenticationMethod(uid, pwd), new PrivateKeyAuthenticationMethod(General.RsaKey));
                MemoryStream   outputlisting  = new MemoryStream();

                using (SshClient client = new SshClient(connectionInfo))
                {
                    PipeStream input = new PipeStream();
                    client.Connect();
                    Shell shell = client.CreateShell(input, Console.OpenStandardOutput(), new MemoryStream());
                    shell.Start();

                    var command      = client.CreateCommand(cmd);
                    var asyncExecute = command.BeginExecute();
                    command.OutputStream.CopyTo(outputlisting);
                    command.EndExecute(asyncExecute);
                    client.Disconnect();
                }

                outputlisting.Position = 0;
                StreamReader sr = new StreamReader(outputlisting);
                sAns = sr.ReadToEnd();
                sr.Dispose();
            }
            catch (Exception e)
            {
                errOut = ErrorMessage("RunCommand", e);
            }
            return(sAns);
        }
Beispiel #3
0
        public void CreateShell5_NeverConnected()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
            {
                var          input          = new MemoryStream();
                var          output         = new MemoryStream();
                var          extendedOutput = new MemoryStream();
                const string terminalName   = "vt100";
                const uint   columns        = 80;
                const uint   rows           = 25;
                const uint   width          = 640;
                const uint   height         = 480;
                var          terminalModes  = new Dictionary <TerminalModes, uint>();

                try
                {
                    client.CreateShell(
                        input,
                        output,
                        extendedOutput,
                        terminalName,
                        columns,
                        rows,
                        width,
                        height,
                        terminalModes);
                    Assert.Fail();
                }
                catch (SshConnectionException ex)
                {
                    Assert.IsNull(ex.InnerException);
                    Assert.AreEqual("Client not connected.", ex.Message);
                }
            }
        }
Beispiel #4
0
 public void Connect()
 {
     client.Connect();
     shell = client.CreateShell(input, output, extendedOuput);
     shell.Start();
     outputReader = new StreamPoller(output);
     textUpdater  = outputReader.TextReceived.Subscribe(textReceivedSubject);
 }
Beispiel #5
0
 public void Connect()
 {
     if (!_client.IsConnected)
     {
         _client.Connect();
     }
     shell = _client.CreateShell(input, output, extendedOuput);
     shell.Start();
     outputReader = new StreamPoller(output);
     textUpdater  = outputReader.TextReceived.Subscribe(this);
 }
        /// <summary>
        /// Executes a shell command in the context of a sudo su
        /// </summary>
        public async Task <string> ExecuteShell(List <string> commands)
        {
            Task <string> task;
            var           stream = new MemoryStream(5000);
            var           shell  = _sshclient.CreateShell(Encoding.Default, String.Join(@"\r\n", commands), stream, null);

            shell.Start();
            using (var reader = new StreamReader(stream))
            {
                task = reader.ReadLineAsync();
            }
            return(await task);
        }
Beispiel #7
0
        public void CreateShellTest3()
        {
            ConnectionInfo connectionInfo = null;                          // TODO: Initialize to an appropriate value
            SshClient      target         = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
            Stream         input          = null;                          // TODO: Initialize to an appropriate value
            Stream         output         = null;                          // TODO: Initialize to an appropriate value
            Stream         extendedOutput = null;                          // TODO: Initialize to an appropriate value
            Shell          expected       = null;                          // TODO: Initialize to an appropriate value
            Shell          actual;

            actual = target.CreateShell(input, output, extendedOutput);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Beispiel #8
0
        public void CreateShellTest4()
        {
            ConnectionInfo connectionInfo = null;                          // TODO: Initialize to an appropriate value
            SshClient      target         = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
            Stream         input          = null;                          // TODO: Initialize to an appropriate value
            Stream         output         = null;                          // TODO: Initialize to an appropriate value
            Stream         extendedOutput = 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
            IDictionary <TerminalModes, uint> terminalModes = null;        // TODO: Initialize to an appropriate value
            Shell expected = null;                                         // TODO: Initialize to an appropriate value
            Shell actual;

            actual = target.CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Beispiel #9
0
        public void CreateShell4_NeverConnected()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
            {
                var input          = new MemoryStream();
                var output         = new MemoryStream();
                var extendedOutput = new MemoryStream();

                try
                {
                    client.CreateShell(input, output, extendedOutput);
                    Assert.Fail();
                }
                catch (SshConnectionException ex)
                {
                    Assert.IsNull(ex.InnerException);
                    Assert.AreEqual("Client not connected.", ex.Message);
                }
            }
        }
Beispiel #10
0
        public void Connect(ConnectionSettings connectionSettings)
        {
            try
            {
                //http://www.ragestorm.net/tutorial?id=15
                //https://greenbytes.de/tech/webdav/draft-ietf-httpbis-p7-auth-00.html
                _inStream  = new MemoryStream();
                _outStream = new MemoryStream();

                var assembly = Assembly.GetExecutingAssembly();
                _keyStream = assembly.GetManifestResourceStream(Constants.PrivateKeyFileName);

                var methods = new List <AuthenticationMethod>
                {
                    new PasswordAuthenticationMethod(connectionSettings.User, connectionSettings.Password),
                    new PrivateKeyAuthenticationMethod(connectionSettings.User,
                                                       new PrivateKeyFile(_keyStream, connectionSettings.Password))
                };

                var connection = SystemProxy.Address == null
                    ? new ConnectionInfo(
                    connectionSettings.Host, connectionSettings.Port, connectionSettings.User, methods.ToArray())
                    : new ConnectionInfo(
                    connectionSettings.Host, connectionSettings.Port, connectionSettings.User, ProxyTypes.Http,
                    SystemProxy.Address.Host, SystemProxy.Address.Port, connectionSettings.DomainUser,
                    connectionSettings.DomainPassword, methods.ToArray());

                _ssh = new SshClient(connection);
                _ssh.ConnectionInfo.MaxSessions   = _ssh.ConnectionInfo.MaxSessions * 3;
                _ssh.ConnectionInfo.RetryAttempts = _ssh.ConnectionInfo.RetryAttempts * 2;
                _ssh.ConnectionInfo.Timeout       = new TimeSpan(0, 0, 40);
                _ssh.KeepAliveInterval            = new TimeSpan(0, 0, 100);
                _ssh.ConnectionInfo.Timeout       = new TimeSpan(0, 0, 100);
                _ssh.Connect();
                _forwardedPort = new ForwardedPortLocal(Constants.Localhost, 8082, connectionSettings.Host, 8081);
                _ssh.AddForwardedPort(_forwardedPort);
                _shell = _ssh.CreateShell(Encoding.UTF8, "", _inStream, _outStream);
                _forwardedPort.Start();
                _shell.Start();

                _connected = true;

                if (connectionSettings.SetExplorer)
                {
                    Browsers.Explorer.Setup();
                }
                if (connectionSettings.SetFirefox)
                {
                    Browsers.Firefox.Setup();
                }
            }
            catch (Exception)
            {
                DisposeResources();
                throw;
            }
            finally
            {
                connectionSettings.DomainPassword = string.Empty;
            }
        }
Beispiel #11
0
 public void CreateShellTest3()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
     Stream input = null; // TODO: Initialize to an appropriate value
     Stream output = null; // TODO: Initialize to an appropriate value
     Stream extendedOutput = null; // TODO: Initialize to an appropriate value
     Shell expected = null; // TODO: Initialize to an appropriate value
     Shell actual;
     actual = target.CreateShell(input, output, extendedOutput);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Beispiel #12
0
        public void CreateShell6_NeverConnected()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
            {
                var input = new MemoryStream();
                var output = new MemoryStream();
                var extendedOutput = new MemoryStream();
                const string terminalName = "vt100";
                const uint columns = 80;
                const uint rows = 25;
                const uint width = 640;
                const uint height = 480;
                var terminalModes = new Dictionary<TerminalModes, uint>();
                const int bufferSize = 4096;

                try
                {

                    client.CreateShell(
                        input,
                        output,
                        extendedOutput,
                        terminalName,
                        columns,
                        rows,
                        width,
                        height,
                        terminalModes,
                        bufferSize);
                    Assert.Fail();
                }
                catch (SshConnectionException ex)
                {
                    Assert.IsNull(ex.InnerException);
                    Assert.AreEqual("Client not connected.", ex.Message);
                }
            }
        }
Beispiel #13
0
        public void CreateShell4_NeverConnected()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
            {
                var input = new MemoryStream();
                var output = new MemoryStream();
                var extendedOutput = new MemoryStream();

                try
                {

                    client.CreateShell(input, output, extendedOutput);
                    Assert.Fail();
                }
                catch (SshConnectionException ex)
                {
                    Assert.IsNull(ex.InnerException);
                    Assert.AreEqual("Client not connected.", ex.Message);
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// 控制台控制linux
        /// </summary>
        /// <param name="client"></param>
        /// <param name="commandStr"></param>
        /// <param name="successCallback"></param>
        /// <param name="errorCallback"></param>
        private void ExcuteCommand(SshClient client, string commandStr, Action <string> successCallback, Action <string> errorCallback)
        {
            try
            {
                var inStream     = new Renci.SshNet.Common.PipeStream();
                var outStream    = new MemoryStream();
                var exStream     = new MemoryStream();
                var shell        = client.CreateShell(inStream, outStream, exStream);
                var streamWriter = new StreamWriter(inStream)
                {
                    AutoFlush = true
                };
                shell.Started += (sender, args) =>
                {
                    while (true)
                    {
                        var command = Console.ReadLine();
                        streamWriter.WriteLine(command);
                        streamWriter.Flush();
                    }
                };
                int outIndex = 0;
                var td       = new Thread(() =>
                {
                    while (true)
                    {
                        var length = outStream.Length == 0 ? 0 : outStream.Length;
                        if (length - outIndex == 0)
                        {
                            continue;
                        }
                        byte[] buffer      = new byte[length - outIndex];
                        outStream.Position = outIndex;
                        outStream.Read(buffer, 0, buffer.Length);
                        outIndex = (int)length;
                        Console.WriteLine(Encoding.UTF8.GetString(buffer));
                        Thread.Sleep(1000);
                    }
                });
                td.Start();
                shell.Start();



                //client.ErrorOccurred += (sender, eventArgs) =>
                //{
                //    Console.WriteLine(eventArgs.Exception);
                //};
                //client.HostKeyReceived += (sender, eventArgs) =>
                //{
                //    Console.WriteLine(eventArgs.HostKeyName);
                //};

                //var command = client.CreateCommand(commandStr.ToString());
                //command.CommandTimeout = new TimeSpan(0, 0, 10);
                //command.Execute(commandStr);


                //if (!string.IsNullOrWhiteSpace(command.Error))
                //{
                //    errorCallback(command.Error);
                //    //result.Append(command.Error + "\r\n");
                //}
                //else
                //{
                //    successCallback(command.Result);
                //}
            }
            catch (Exception e1)
            {
                errorCallback(e1.Message);
            }
        }
Beispiel #15
0
 public void InstallLiveService(Action <int, string> resultCallback, bool repair)
 {
     if (IsInstalledService() && !repair)
     {
         return;
     }
     using (SshClient client = new SshClient(_host, _port, _username, _password))
     {
         client.Connect();
         StringBuilder installLogBuilder = new StringBuilder();
         try
         {
             var inStream     = new Renci.SshNet.Common.PipeStream();
             var outStream    = new MemoryStream();
             var exStream     = new MemoryStream();
             var shell        = client.CreateShell(inStream, outStream, exStream);
             var streamWriter = new StreamWriter(inStream)
             {
                 AutoFlush = true
             };
             var daemonThread = new Thread(() =>
             {
                 int outIndex = 0;
                 while (true)
                 {
                     Thread.Sleep(200);
                     var length = outStream.Length == 0 ? 0 : outStream.Length;
                     if (length - outIndex == 0)
                     {
                         continue;
                     }
                     byte[] buffer      = new byte[length - outIndex];
                     outStream.Position = outIndex;
                     outStream.Read(buffer, 0, buffer.Length);
                     outIndex   = (int)length;
                     var result = Encoding.UTF8.GetString(buffer);
                     installLogBuilder.AppendLine(result);
                     Console.WriteLine(result);
                     if (result.Contains("Live Stream Service Installed!"))
                     {
                         shell.Stop();
                         shell.Dispose();
                         break;
                     }
                 }
                 resultCallback.Invoke(0, "Install Success.");
                 Thread.CurrentThread.Abort();
             });
             shell.Starting += (state, arg) =>
             {
             };
             shell.ErrorOccurred += (state, arg) =>
             {
             };
             shell.Stopped += (state, arg) =>
             {
             };
             shell.Stopping += (state, arg) =>
             {
             };
             shell.Started += (sender, args) =>
             {
                 daemonThread.Start();
                 Thread.Sleep(5000);
                 var sb = new StringBuilder();
                 sb.AppendLine(@"echo Start Stream Service Installed!");
                 sb.AppendLine("yum install -y autoconf automake cmake freetype-devel gcc gcc-c++ git libtool make mercurial nasm pkgconfig zlib - devel");
                 sb.AppendLine("yum update -y nss curl libcurl");
                 sb.AppendLine("git clone https://github.com/ossrs/srs");
                 sb.AppendLine("cd ~/srs/trunk");
                 sb.AppendLine("./configure --full&& make");
                 sb.AppendLine(@"echo Live Stream Service Installed!");
                 streamWriter.WriteLine(sb);
                 streamWriter.Flush();
                 Thread.CurrentThread.Join();
             };
             shell.Start();
         }
         catch (Exception e)
         {
             resultCallback(-1, e.Message);
             client.Disconnect();
             client.Dispose();
             throw;
         }
         finally
         {
             //todo: save installLogBuilder
         }
     }
 }
Beispiel #16
0
        /*
         * 6.7.  Window Dimension Change Message
         *
         * When the window (terminal) size changes on the client side, it MAY
         * send a message to the other side to inform it of the new dimensions.
         *
         * byte      SSH_MSG_CHANNEL_REQUEST
         * uint32    recipient channel
         * string    "window-change"
         * boolean   FALSE
         * uint32    terminal width, columns
         * uint32    terminal height, rows
         * uint32    terminal width, pixels
         * uint32    terminal height, pixels
         */

        private void connectButton_Click(object sender, EventArgs e)
        {
            if (client != null && client.IsConnected)
            {
                return;
            }

            if (client != null)
            {
                client.Dispose();
            }

            host_textbox.Enabled         =
                user_textbox.Enabled     =
                    pass_textbox.Enabled = false;

            client = new SshClient(host_textbox.Text, user_textbox.Text, pass_textbox.Text)
            {
                KeepAliveInterval = new TimeSpan(0, 2, 0)
            };
            client.HostKeyReceived += Client_HostKeyReceived;
            client.ErrorOccurred   += Client_ErrorOccurred;

            keyboardStream = new KeyboardStream();
            var screenS = new ScreenStream();

            var tSize = terminalFrameBuffer.EstimateScreenSize();

            screen = new libVT100.TerminalFrameBuffer(tSize.X, tSize.Y);

            terminalFrameBuffer.BoundScreen = screen;
            terminalFrameBuffer.LegendLabel = terminalLegend;

            terminalFrameBuffer.Init();

            vt100            = new AnsiDecoder();
            vt100.Output    += Vt100_Output;
            screenS.InjectTo = vt100;
            vt100.Encoding   = new UTF8Encoding(); // Encoding.GetEncoding("utf8");
            vt100.Subscribe(screen);

            try
            {
                client.Connect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Connect: " + ex.Message, "Connect Error", MessageBoxButtons.OK);
                client.Dispose();
                client = null;

                return;
            }

            checkLoginState();

            if (terminalFrameBuffer.CanFocus)
            {
                terminalFrameBuffer.Focus();
            }

            var termModes = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>();

            var shell = client.CreateShell(keyboardStream, screenS, screenS,
                                           "VRTerm", (uint)tSize.X, (uint)tSize.Y, (uint)terminalFrameBuffer.Width, (uint)terminalFrameBuffer.Height, termModes);



            shell.Start();
        }
Beispiel #17
0
 public void CreateShellTest5()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
     Stream input = null; // TODO: Initialize to an appropriate value
     Stream output = null; // TODO: Initialize to an appropriate value
     Stream extendedOutput = 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
     IDictionary<TerminalModes, uint> terminalModes = null; // TODO: Initialize to an appropriate value
     int bufferSize = 0; // TODO: Initialize to an appropriate value
     Shell expected = null; // TODO: Initialize to an appropriate value
     Shell actual;
     actual = target.CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }