private static void connect(string hostName, string userName, string password)
        {
            if (client != null && client.IsConnected)
            {
                return;
            }


            var connectionInfo = new KeyboardInteractiveConnectionInfo(hostName, userName);

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

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

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

            shellCommand("python", null);

            using (var sr = new System.IO.StreamReader("queryJoints.py"))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    pythonCommand(line);
                }
            }
        }
Exemple #2
0
        public void Connect()
        {
            if (_client != null && _client.IsConnected)
            {
                CloudLog.Warn("{0} already connected", GetType().Name);
                return;
            }

            _reconnect = true;

            var info = new KeyboardInteractiveConnectionInfo(_address, _port, _username);

            info.AuthenticationPrompt += OnPasswordPrompt;

            _client = new SshClient(info);
            _client.ErrorOccurred +=
                (sender, args) => CloudLog.Exception(args.Exception, "SshClient.ErrorOccurred Event");
            _client.HostKeyReceived +=
                (sender, args) =>
                CloudLog.Notice("{0} HostKeyReceived: {1}, can trust = {2}", GetType().Name, args.HostKeyName,
                                args.CanTrust);

            _sshProcess = new Thread(SshCommsProcess, null, Thread.eThreadStartOptions.CreateSuspended)
            {
                Name     = "CodecSshClient Comms Handler",
                Priority = Thread.eThreadPriority.MediumPriority
            };

            _sshProcess.Start();
        }
        public void Test_KeyboardInteractiveConnectionInfo()
        {
            var host     = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example KeyboardInteractiveConnectionInfo AuthenticationPrompt
            var connectionInfo = new KeyboardInteractiveConnectionInfo(host, username);
            connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
            {
                System.Console.WriteLine(e.Instruction);

                foreach (var prompt in e.Prompts)
                {
                    Console.WriteLine(prompt.Request);
                    prompt.Response = Console.ReadLine();
                }
            };

            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
Exemple #4
0
        //获取一个可用的SFTPClient
        private SftpClient GetAvailableSFTP()
        {
            //关闭之前的
            //Close();
            try
            {
                var connectionInfo = new KeyboardInteractiveConnectionInfo(ipAddress, 22, loginUser);
                connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                {
                    foreach (var prompt in e.Prompts)
                    {
                        if (prompt.Request.Equals("Password:"******""));
            }
            return(null);
        }
        public void Test_KeyboardInteractiveConnectionInfo()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example KeyboardInteractiveConnectionInfo AuthenticationPrompt
            var connectionInfo = new KeyboardInteractiveConnectionInfo(host, username);
            connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
            {
                System.Console.WriteLine(e.Instruction);

                foreach (var prompt in e.Prompts)
                {
                    Console.WriteLine(prompt.Request);
                    prompt.Response = Console.ReadLine();
                }
            };

            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            for (int i = 11; i < 255; i++)
            {
                Console.WriteLine("------------------------------------");

                try
                {
                    string ip             = "192.168.0." + i.ToString();
                    string username       = "******";
                    int    port           = 22;
                    var    connectionInfo = new KeyboardInteractiveConnectionInfo(ip, port, username);
                    connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.ToLower().Contains("password"))
                            {
                                prompt.Response = "password";
                            }
                        }
                    };
                    SshClient s = new SshClient(connectionInfo);

                    s.Connect();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("IP: " + i.ToString());
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine("------------------------------------");
            }
        }
Exemple #7
0
        public void Connect()
        {
            if (_client != null && _client.IsConnected)
            {
                CloudLog.Warn("{0} already connected", GetType().Name);
                return;
            }

            _reconnect = true;

            var info = new KeyboardInteractiveConnectionInfo(_address, 22, _username);

            info.AuthenticationPrompt += OnPasswordPrompt;

            _client = new SshClient(info);
            _client.ErrorOccurred   += (sender, args) => CrestronConsole.PrintLine("ErrorOccurred: {0}", args.Exception.Message);
            _client.HostKeyReceived +=
                (sender, args) => CrestronConsole.PrintLine("HostKeyReceived: {1}, can trust = {0}", args.CanTrust,
                                                            args.HostKeyName);

            _sshProcess = new Thread(SshCommsProcess, null, Thread.eThreadStartOptions.CreateSuspended)
            {
                Name     = "Tesira SSH Comms Handler",
                Priority = Thread.eThreadPriority.HighPriority
            };

            _sshProcess.Start();
        }
 [Ignore] // placeholder for actual test
 public void DisposeTest()
 {
     string host = string.Empty; // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username); // TODO: Initialize to an appropriate value
     target.Dispose();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
        [Ignore] // placeholder for actual test
        public void KeyboardInteractiveConnectionInfoConstructorTest7()
        {
            string host     = string.Empty; // TODO: Initialize to an appropriate value
            string username = string.Empty; // TODO: Initialize to an appropriate value
            KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
        [Ignore] // placeholder for actual test
        public void DisposeTest()
        {
            string host     = string.Empty;                                                                   // TODO: Initialize to an appropriate value
            string username = string.Empty;                                                                   // TODO: Initialize to an appropriate value
            KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username); // TODO: Initialize to an appropriate value

            target.Dispose();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
        [Ignore] // placeholder for actual test
        public void KeyboardInteractiveConnectionInfoConstructorTest3()
        {
            string     host      = string.Empty;     // TODO: Initialize to an appropriate value
            string     username  = string.Empty;     // TODO: Initialize to an appropriate value
            ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
            string     proxyHost = string.Empty;     // TODO: Initialize to an appropriate value
            int        proxyPort = 0;                // TODO: Initialize to an appropriate value
            KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username, proxyType, proxyHost, proxyPort);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
 public void KeyboardInteractiveConnectionInfoConstructorTest2()
 {
     string host = string.Empty; // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     ProxyTypes proxyType = new ProxyTypes(); // TODO: Initialize to an appropriate value
     string proxyHost = string.Empty; // TODO: Initialize to an appropriate value
     int proxyPort = 0; // TODO: Initialize to an appropriate value
     string proxyUsername = string.Empty; // TODO: Initialize to an appropriate value
     KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username, proxyType, proxyHost, proxyPort, proxyUsername);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
        public void powerOFFUnixMachine(GetWorkstationsToBePoweredOFF_Result workstation)
        {
            /*var connectionInfo = new KeyboardInteractiveConnectionInfo("129.21.70.249", 22, "christianpichardo");
             *
             * connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
             * {
             *  foreach (var prompt in e.Prompts)
             *  {
             *      if (prompt.Request.Equals("Password:"******"123456";
             *      }
             *  }
             * };
             *
             * var ssh = new SshClient(connectionInfo);
             *
             *  ssh.Connect();
             *  var cmd = ssh.RunCommand("who");
             *  //return cmd.Result;
             */



            var connectionInfo = new KeyboardInteractiveConnectionInfo("129.21.70.249", 22, "root");

            //var sshClient = new SshClient("129.21.70.249", "christianpichardo", "123456"); //name, username, password

            connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
            {
                foreach (var prompt in e.Prompts)
                {
                    if (prompt.Request.Equals("Password:"******"root";
                    }
                }
            };

            var sshClient = new SshClient(connectionInfo);

            sshClient.Connect();

            var cmd    = sshClient.RunCommand("shutdown -h +1 'Shutting down soon!'");
            var output = cmd.Result;

            sshClient.Disconnect();
        }
Exemple #14
0
        public PythonConnection(string hostName, string userName, string password)
        {
            var connectionInfo = new KeyboardInteractiveConnectionInfo(hostName, userName);

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

            client = new SshClient(connectionInfo);

            client.Connect();

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

            shellCommand("python", null);
        }
        /// <summary>
        /// Creates the appropriate file system driver for accessing the given
        /// <paramref name="path"/>
        /// </summary>
        /// <param name="path">
        /// A fully qualified path.
        /// </param>
        /// <returns>
        /// If <paramref name="path"/> starts with 'sftp', an
        /// <see cref="SFTPFileSystemDriver"/> will be used. If the path is
        /// null, <see cref="NullFileSystemDriver"/> will be used. Otherwise,
        /// a local path will be assumed, which thus makes use of
        /// <see cref="StandardFsDriver"/>
        /// </returns>
        public static IFileSystemDriver GetFileSystemDriver(string path)
        {
            if (fsDrivers.ContainsKey(path))
            {
                if (fsDrivers[path].IsDisposed)
                {
                    fsDrivers.Remove(path);
                }
                else
                {
                    return(fsDrivers[path]);
                }
            }

            IFileSystemDriver fsDriver;
            string            sftpString = "sftp://";

            if (path.StartsWith(sftpString))
            {
                try {
                    string s    = path.Substring(sftpString.Length);
                    string user = s.Substring(0, s.IndexOf('@'));

                    s = s.Substring(s.IndexOf('@') + 1);
                    int hostPartEnd = s.IndexOf(':');

                    string host;
                    string relPath;
                    if (hostPartEnd >= 0)
                    {
                        host    = s.Substring(0, hostPartEnd);
                        relPath = s.Substring(s.IndexOf(':') + 1);
                    }
                    else
                    {
                        host    = s;
                        relPath = "/";
                    }

                    KeyboardInteractiveConnectionInfo ci =
                        new KeyboardInteractiveConnectionInfo(host, user);
                    ci.AuthenticationPrompt +=
                        delegate(object sender, AuthenticationPromptEventArgs arg) {
                        var prompt = arg.Prompts.SingleOrDefault(p => p.Request == "Password: "******"@" + host);
                        }
                    };
                    ci.Timeout = TimeSpan.FromSeconds(15);

                    fsDriver = new SFTPFileSystemDriver(ci, relPath);
                } catch (Exception) {
                    throw new ArgumentException(String.Format(
                                                    "Given path '{0}' has an invalid format", path));
                }
            }
            else if (File.Exists(path) || Directory.Exists(path))
            {
                fsDriver = new StandardFsDriver(path);
            }
            else if (path == null)
            {
                fsDriver = NullFileSystemDriver.Instance;
            }
            else
            {
                throw new IOException(String.Format(
                                          "Could not find or access a database located at '{0}'", path));
            }

            fsDrivers.Add(path, fsDriver);
            return(fsDriver);
        }
 [Ignore] // placeholder for actual test
 public void KeyboardInteractiveConnectionInfoConstructorTest7()
 {
     string host = string.Empty; // TODO: Initialize to an appropriate value
     string username = string.Empty; // TODO: Initialize to an appropriate value
     KeyboardInteractiveConnectionInfo target = new KeyboardInteractiveConnectionInfo(host, username);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Exemple #17
0
        /// <summary>
        /// Establishes the connection to the server, using the specified <paramref name="terminal"/> for connection initialization (authentication, etc.).
        /// </summary>
        /// <param name="terminal">The terminal to use for connection initialization.</param>
        /// <returns>A value indicating whether the connection was successfully established.</returns>
        /// <exception cref="ObjectDisposedException">The connection object is already disposed.</exception>
        /// <exception cref="InvalidOperationException">The connection object is currently connected.</exception>
        public async Task <bool> ConnectAsync(IConnectionInitializingTerminal terminal)
        {
            this.CheckDisposed();
            this.MustBeConnected(false);

            Lazy <string> username = new Lazy <string>(() =>
            {
                if (string.IsNullOrEmpty(this.connectionData.Username))
                {
                    return(terminal.ReadLineAsync("Username: "******"Username: "******"Password: "******"Password expired for user " + e.Username);
                            do
                            {
                                var readNewPassword1Task = terminal.ReadLineAsync("New password: "******"Repeat new password: "******"Performing keyboard-interactive authentication.");
                            }

                            if (!string.IsNullOrEmpty(e.Instruction))
                            {
                                terminal.WriteLine(e.Instruction);
                            }

                            foreach (var prompt in e.Prompts)
                            {
                                var readLineTask = terminal.ReadLineAsync(prompt.Request, echo: prompt.IsEchoed);
                                readLineTask.Wait();
                                prompt.Response = readLineTask.Result;
                            }
                        };
                        connectionInfo = keyboardInteractiveConnectionInfo;
                        break;

                    case Model.AuthenticationType.PrivateKey:
                        if (this.privateKeyData == null)
                        {
                            throw new Exception("Private Key '" + connectionData.PrivateKeyName + "' not found. Please correct the authentication details of the connection.");
                        }

                        PrivateKeyFile privateKey;

                        try
                        {
                            using (var privateKeyStream = new MemoryStream(privateKeyData.Data))
                            {
                                privateKey = new PrivateKeyFile(privateKeyStream);
                            }
                        }
                        catch (SshPassPhraseNullOrEmptyException)
                        {
                            privateKey = null;
                        }

                        // In the normal PrivateKey authentication there is only a connection-local PrivateKeyAgent.
                        var localPprivateKeyAgent = new Lazy <PrivateKeyAgent>(() =>
                        {
                            terminal.WriteLine("Performing authentication with Private Key '" + connectionData.PrivateKeyName + "'.");

                            if (privateKey == null)
                            {
                                string privateKeyPassword = terminal.ReadLineAsync("Private Key password: "******"Wrong Private Key password, please try again.", ex);
                                    }
                                }
                            }

                            var pka = new PrivateKeyAgent();
                            pka.AddSsh2(privateKey.HostKey, connectionData.PrivateKeyName);
                            return(pka);
                        });

                        var privateKeyConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, localPprivateKeyAgent);
                        connectionInfo = privateKeyConnectionInfo;

                        break;

                    case AuthenticationType.PrivateKeyAgent:
                        if (PrivateKeyAgentManager.PrivateKeyAgent.ListSsh2().Count == 0)
                        {
                            throw new SshAuthenticationException("The private key agent doesn't contain any private keys.");
                        }

                        var globalPrivateKeyAgent = new Lazy <PrivateKeyAgent>(() =>
                        {
                            var pka = PrivateKeyAgentManager.PrivateKeyAgent;
                            terminal.WriteLine("Performing private key agent authentication.");
                            return(pka);
                        });

                        var privateKeyAgentConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, globalPrivateKeyAgent);
                        connectionInfo = privateKeyAgentConnectionInfo;
                        if (connectionData.PrivateKeyAgentForwarding == true)
                        {
                            forwardedPrivateKeyAgent = globalPrivateKeyAgent;
                            terminal.WriteLine("Agent forwarding is enabled.");
                        }

                        break;

                    default:
                        throw new NotImplementedException("Authentication method '" + this.connectionData.Authentication + "' not implemented.");
                    }

                    connectionInfo.AuthenticationBanner += (sender, e) =>
                    {
                        terminal.WriteLine(e.BannerMessage.Replace("\n", "\r\n"));
                    };

                    this.client = new SshClient(connectionInfo);
                    this.client.HostKeyReceived += (s, e) =>
                    {
                        string fingerprint = string.Join(":", e.FingerPrint.Select(b => b.ToString("x2")));

                        bool trustHostKey = true;
                        bool storeHostKey = false;

                        string newHostKey = string.Join(null, e.HostKey.Select(b => b.ToString("x2")));
                        if (oldHostKey == null)
                        {
                            terminal.WriteLine("Remote Terminal has not yet cached a host key for this server.");
                            terminal.WriteLine("Host key's fingerprint: " + fingerprint);
                            terminal.WriteLine("Please make sure the fingerprint matches the server's actual host key.");
                            trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?");
                            if (trustHostKey)
                            {
                                storeHostKey = QueryYesNo(terminal, "Do you want to store this host key in the cache?");
                            }
                        }
                        else if (oldHostKey != newHostKey)
                        {
                            terminal.WriteLine("POSSIBLE SECURITY BREACH DETECTED!");
                            terminal.WriteLine("Remote Terminal has cached another host key for this server.");
                            terminal.WriteLine("This could mean one of two things:");
                            terminal.WriteLine(" * the server's host key was changed by an administrator");
                            terminal.WriteLine(" * another computer is trying to intercept your connection");
                            terminal.WriteLine("Host key's new fingerprint: " + fingerprint);
                            trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?");
                            if (trustHostKey)
                            {
                                storeHostKey = QueryYesNo(terminal, "Do you want to update the cache with the new host key?");
                            }
                        }

                        e.CanTrust = trustHostKey;
                        if (trustHostKey)
                        {
                            oldHostKey = newHostKey;
                        }

                        if (storeHostKey)
                        {
                            HostKeysDataSource.AddOrUpdate(this.connectionData.Host, this.connectionData.Port, newHostKey);
                        }
                    };

                    this.client.ConnectionInfo.Timeout = new TimeSpan(0, 15, 0);
                    await Task.Run(() => { this.client.Connect(); });

                    this.client.ConnectionInfo.Timeout = new TimeSpan(0, 1, 0);

                    var terminalModes = new Dictionary <TerminalModes, uint>();
                    terminalModes[TerminalModes.TTY_OP_ISPEED] = 0x00009600;
                    terminalModes[TerminalModes.TTY_OP_OSPEED] = 0x00009600;
                    this.stream = this.client.CreateShellStream(terminal.TerminalName, (uint)terminal.Columns, (uint)terminal.Rows, 0, 0, 1024, forwardedPrivateKeyAgent.Value, terminalModes.ToArray());

                    this.reader           = new StreamReader(this.stream);
                    this.writer           = new StreamWriter(this.stream);
                    this.writer.AutoFlush = true;
                    return(true);
                }
                catch (SshConnectionException ex)
                {
                    terminal.WriteLine(ex.Message);
                    retry = false;
                }
                catch (SshAuthenticationException ex)
                {
                    terminal.WriteLine(ex.Message);
                    if (connectionData.Authentication == AuthenticationType.PrivateKeyAgent)
                    {
                        terminal.WriteLine("Please load the necessary private key(s) into the private key agent.");
                        retry = false;
                    }
                    else
                    {
                        retry = true;
                    }
                }
                catch (Exception ex)
                {
                    terminal.WriteLine(ex.Message);
                    retry = false;
                }

                if (!retry || numRetries++ > 5)
                {
                    return(false);
                }
            }while (true);
        }