Provides client connection to SSH server.
Inheritance: BaseClient
        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);
            }
        }
Beispiel #2
5
        static void Main(string[] args)
        {
            Console.WriteLine("fd");

            try
            {
                ssh = new SshClient("10.141.3.110", "root", "ismail");
                ssh.Connect();
                 //status = true;
                 //timer_enable();
            }
            //catch (Exception ex)
            // {
            //    Console.Write(ex.Message);
            //}

            catch { }

               if (true)
            try
            {
                stream = ssh.CreateShellStream("xterm", 80, 50, 1024, 1024, 1024);
                Thread.Sleep(100);
                stream.WriteLine("telnet localhost 6571");
                Thread.Sleep(100);
            }
            catch (Exception)
            {
                Console.WriteLine("hata");
            }

            Console.ReadKey();
        }
Beispiel #3
3
    static void Main(string[] args)
    {

        // Setup Credentials and Server Information
        ConnectionInfo ConnNfo = new ConnectionInfo("10.141.3.110", 22, "root",
            new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("root","ismail"),

                
            }
        );



        // Execute (SHELL) Commands
        using (var sshclient = new SshClient(ConnNfo))
        {
            sshclient.Connect();
            //
            // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
            Console.WriteLine("telnet localhost 6571");
            Console.WriteLine("denemeeeeeee");
            Console.WriteLine("deneme2");
            //Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
            //Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
            //Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
            sshclient.Disconnect();
        }
        Console.ReadKey();
    }
Beispiel #4
2
        public void Connect(string remoteIp, string username, string password)
        {
            sshClient = new SshClient(remoteIp, username, password);
            scpClient = new ScpClient(remoteIp, username, password);

            Connect();
        }
Beispiel #5
1
        /// <summary>
        /// Copy from source to target
        /// </summary>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            Debug.WriteLine("CopyCommand");

            var scp = new ScpClient(client.ConnectionInfo) {BufferSize = 8*1024};

            Debug.WriteLine("Connect");

            // Need this or we get Dropbear exceptions...
            scp.Connect();

            Debug.WriteLine("Upload");

            bool status = false;
            try
            {
                scp.Upload(new FileInfo(Source), Target);
                status = true;
            } catch(Exception e)
            {
                Logger.Warn("Exception in SCP transfer: " + e.Message);
            }

            Debug.WriteLine("Done");

            return status;
        }
        //выполнение списка команд
        public override void ExecuteCommands(List<string> commands)
        {
            try
            {
                using (var sshclient = new SshClient(connInfo))
                {
                    sshclient.Connect();
                    //если требуется привилегированный режим
                    if (_host.enableMode)
                    {
                        ExecuteEnableModeCommands(sshclient, commands);
                    }
                    //если не требуется привилегированный режим
                    else
                    {
                        foreach (string command in commands)
                        {
                            Execute(sshclient, command);
                        }
                    }
                    sshclient.Disconnect();
                }
                _success = true;
            }
            catch (Exception ex)//заменить на проброс исключения
            {
                _success = false;
                _listError.Add(ex.Message);
            }

        }
Beispiel #7
1
        private void ButtonConnectClick(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "";
            Application.DoEvents();

            _client = new SshClient(textBoxIPAddr.Text, textBoxLogin.Text, textBoxPassword.Text);

            _client.Connect();
            toolStripStatusLabel1.Text = "Connection: " + _client.IsConnected;
            Application.DoEvents();

            bool stat;
            string output;

            var script = new Script(Globals.ScriptFileName);

                script.Initialisation.SshClient = _client;
//                script.Initialisation.OnUpdateUI -= testScript_OnUpdateUI;
  //              script.Initialisation.OnUpdateUI += testScript_OnUpdateUI;

                stat = script.Initialisation.Execute(textBoxIPAddr.Text, textBoxLogin.Text,
                                                     textBoxPassword.Text, out output);

            toolStripStatusLabel1.Text = "Copy status: " + stat;
        }
        private void LocalVmToolStripMenuItemClick(object sender, EventArgs e)
        {
            var connectionInfo = new PasswordConnectionInfo(host, 22, username, password);
            connectionInfo.AuthenticationBanner += ConnectionInfoAuthenticationBanner;
            connectionInfo.PasswordExpired += ConnectionInfoPasswordExpired;
            sshClient = new SshClient(connectionInfo);
            sshClient.ErrorOccurred += SshClientErrorOccurred;
            Log(string.Format("Connecting to {0}:{1} as {2}", connectionInfo.Host, connectionInfo.Port, connectionInfo.Username));

            try
            {
                sshClient.Connect();
                var tunnel = sshClient.AddForwardedPort<ForwardedPortLocal>("localhost", 20080, "www.google.com", 80);
                tunnel.Start();

            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }
            finally
            {
                sshClient.Dispose();
            }
            Log("Connected");
            sshClient.ForwardedPorts.ToList().ForEach(p => Log(string.Format("SSH tunnel: {0}:{1} --> {2}:{3}", p.BoundHost, p.BoundPort, p.Host, p.Port) ));
        }
		public SshCommandHelper(string IPAddress, ManualResetEvent executed = null, IConsole console = null, bool verbose = false)
		{
			_executed = executed;
			_console = console;
			_verbose = verbose;
			_sshClient = new SshClient(IPAddress, "root", "");
		}
Beispiel #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("fd");

            try
            {
                ssh = new SshClient("10.141.3.110", "root", "ismail");
                ssh.Connect();
                //status = true;
                //timer_enable();
            }
            //catch (Exception ex)
            // {
            //    Console.Write(ex.Message);
            //}

            catch { }

            if (true)
            {
                try
                {
                    stream = ssh.CreateShellStream("xterm", 80, 50, 1024, 1024, 1024);
                    Thread.Sleep(100);
                    stream.WriteLine("telnet localhost 6571");
                    Thread.Sleep(100);
                }
                catch (Exception)
                {
                    Console.WriteLine("hata");
                }
            }

            Console.ReadKey();
        }
Beispiel #11
0
        private void button1_Click(object sender, EventArgs e)
        {
            string host = textBoxServer.Text.Trim();
            string userName = textBoxUserName.Text.Trim();
            string psw = textBoxPassword.Text.Trim();
            string url = textBoxCoomand.Text.Trim();
            string location = @" -P  " + textBoxLocation.Text.Trim();
            string finalCommand = @"wget -bqc '" + url + "' " + location + " ";
            ConnectionInfo conInfo = new ConnectionInfo(host, 22, userName, new AuthenticationMethod[]{
                new PasswordAuthenticationMethod(userName,psw)
            });
            SshClient client = new SshClient(conInfo);
            try
            {
                client.Connect();
                var outptu = client.RunCommand(finalCommand);
            }
            catch (Exception ex)
            {
                textBoxDisplay.Text = ex.Message;
                throw;
            }

            client.Disconnect();
            client.Dispose();
            SetLastValues(host, userName, psw, textBoxLocation.Text.Trim());
        }
Beispiel #12
0
 public void Run(string cmd, string host)
 {
     try
     {
         using (SshClient c = new SshClient(host, m_userName, m_userPassword))
         {
             Log.DebugFormat("Connecting to {0} with command: {1}", host, cmd );
             c.Connect();
             SshCommand ssh = c.RunCommand(cmd);
             ExitStatus = ssh.ExitStatus;
             Result = ssh.Result;
             c.Disconnect();
             if (Result.Length == 0)
             {
                 Log.DebugFormat("Disconnecting from {0} with exit status: {1} (result is empty)", host, ExitStatus );
             }
             else
             {
                 Log.DebugFormat("Disconnecting from {0} with exit status {1} result is: " + Environment.NewLine + "{2}", host, ExitStatus, Result);
             }
         }
     }
     catch (Exception ex)
     {
         Log.ErrorFormat("Failed to connect to {0} because: {1}", host, ex);
         ExitStatus = -1;
         Result = null;
     }
 }
Beispiel #13
0
        protected override IEnumerable<statistics> DoSystemUniquePool()
        {
            using (var client = new SshClient(host, userid, pass))
            {
                client.HostKeyReceived += (sender, e) => {
                    e.CanTrust = true;
                };

                client.Connect();

                foreach (var stats in new IEnumerable<statistics>[] {
                    GetMemInfo(client),
                    GetCpuMemUsage(client),
                    GetVolInfo(client),
                    GetMachineType(client),
                    GetUpSeconds(client),
                    GetInterfaceIP(client),
                    GetDMI(client),
                    GetCPUCores(client),
                })
                {
                    foreach (var s in stats)
                    {
                        s.begintime = s.endtime = DateTime.Now;
                        yield return s;
                    }
                }

                client.Disconnect();
            }
            yield break;
        }
Beispiel #14
0
        private static String ExecuteCommand(SshClient sshClient, String command)
        {
            if (!sshClient.IsConnected)
                sshClient.Connect();

            return sshClient.CreateCommand(command).Execute();
        }
Beispiel #15
0
        /// <summary>
        /// Copy from source to target
        /// </summary>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            bool success = false;
            try
            {
                Debug.WriteLine("ExtractCommand");

                var command1 = client.RunCommand("tar xzvf " + Target);
                var s1 = command1.Result;
                Output = s1;

                var command2 = client.RunCommand("echo $?");
                var s2 = command2.Result;
                
                var arrRsp = s2.Split(new[] {"\n"}, StringSplitOptions.None);

                if(arrRsp.Length > 0)
                    if (arrRsp[0] == "0")
                        success = true;

            } catch(Exception e)
            {
                Logger.Warn("Exception extracting archive: " +e.Message);
            }
            return success;
        }
 public SshFactory(String host, String username, String password)
 {
     _connection = new SshClient(host, username, password);
     _connection.Connect();
     _sftp = new SftpClient(_connection.ConnectionInfo);
     _sftp.Connect();
 }
        public static void SSHConnect()
        {
            string host = App.ViewModel.settings.SSHServerSetting;
            int port = Convert.ToInt32(App.ViewModel.settings.SSHPortSetting);
            string username = App.ViewModel.settings.SSHAccountSetting;

            if (App.ViewModel.settings.SSHUseKeySetting)
            {
                string sshkey = App.ViewModel.settings.SSHKeySetting;

                byte[] s = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(sshkey);
                MemoryStream m = new MemoryStream(s);

                client = new SshClient(host, port, username, new PrivateKeyFile(m));
            }
            else
            {
                string password = App.ViewModel.settings.SSHPasswordSetting;

                client = new SshClient(host, port, username, password);
            }

            System.Diagnostics.Debug.WriteLine("SSH client done");
            client.Connect();
            System.Diagnostics.Debug.WriteLine("SSH connect done");
        }
Beispiel #18
0
        /// <summary>
        /// ListenPort
        /// </summary>
        /// <returns></returns>
        public string ListenPort()
        {
            Constants.log.Info("Entering SshListener ListenPort Method!");
            string response = string.Empty;

            if (_sshClient == null && _connInfo == null)
            {
                Constants.log.Info("Calling SshListener InitializeListener Method!");
                InitializeListener();
            }

            try
            {
                _sshClient = new SshClient(_connInfo);
                _sshClient.Connect();
                response = _sshClient.CreateCommand(this.Command).Execute();
            }
            catch (Exception ex)
            {
                Constants.log.Error(ex.Message);
                response = ex.Message;
            }

            Constants.log.Info("Exiting SshListener ListenPort Method!");
            return response;
        }
Beispiel #19
0
        public override NodeResult Run()
        {
            if (string.IsNullOrEmpty(host.Value) || string.IsNullOrEmpty(user.Value) || string.IsNullOrEmpty(command.Value))
                return NodeResult.Fail;

            try
            {
                SshClient sshClient = new SshClient(host.Value, port.Value, user.Value, password.Value);
                sshClient.Connect();

                Renci.SshNet.SshCommand sshCommand = sshClient.RunCommand(command.Value);
                Log.Info(sshCommand.CommandText);

                if (!string.IsNullOrWhiteSpace(sshCommand.Result))
                    Log.Warning(sshCommand.Result);
                if (!string.IsNullOrWhiteSpace(sshCommand.Error))
                    Log.Error(sshCommand.Error);
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return NodeResult.Fail;
            }

            return NodeResult.Success;
        }
Beispiel #20
0
        public static SshSession AddToSshSessionCollection(SshClient sshclient, SessionState pssession)
        {
            //Set initial variables
            var obj = new SshSession();
            var sshSessions = new List<SshSession>();
            var index = 0;

            // Retrieve existing sessions from the global variable.
            var sessionvar = pssession.PSVariable.GetValue("Global:SshSessions") as List<SshSession>;

            // If sessions exist we set the proper index number for them.
            if (sessionvar != null && sessionvar.Count > 0)
            {
                sshSessions.AddRange(sessionvar);

                // Get the SessionId of the last item and count + 1
                SshSession lastSession = sshSessions[sshSessions.Count - 1];
                index = lastSession.SessionId + 1;
            }

            // Create the object that will be saved
            obj.SessionId = index;
            obj.Host = sshclient.ConnectionInfo.Host;
            obj.Session = sshclient;
            sshSessions.Add(obj);

            // Set the Global Variable for the sessions.
            pssession.PSVariable.Set((new PSVariable("Global:SshSessions", sshSessions, ScopedItemOptions.AllScope)));

            return obj;
        }
Beispiel #21
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // Note disposing has been done.
                _disposed = true;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    if (_sshClient != null)
                    {
                        _sshClient.Dispose();
                    }

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

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                _sshClient     = null;
                _sshConnection = null;
            }
        }
        public void GetUsers(object sender, BackgroundWorker worker, Delegate sendUsers)
        {
            foreach (string host in SshSettings.Hosts())
            {
                if (worker.CancellationPending)
                    break;

                List<SshUser> users = new List<SshUser>();
                using (SshClient ssh = new SshClient(_currentUser.GetPasswordConenctionInfo(String.Concat(host, SshSettings.Domain))))
                {
                    try
                    {
                        ssh.Connect();
                        string response = ssh.RunCommand("who -u").Execute();
                        // TODO: Parse response.
                        ParseWhoResponse(response, host, ref users);
                        if (users.Count > 0)
                            ((System.Windows.Forms.Form) sender).Invoke(sendUsers, users);
                    }
                    catch (Exception ex)
                    {
                        if (ex is SshException || ex is SocketException)
                        {
                            if (ssh.IsConnected)
                                ssh.Disconnect();
                            ssh.Dispose();
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
        }
Beispiel #23
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public virtual bool Execute()
        {
            var decryptedPassword = EncrytionHelper.Decrypt(SshPassword);
            var client            = new Renci.SshNet.SshClient(SshHost, SshLogin, decryptedPassword);

            client.Connect();

            var termkvp = new Dictionary <TerminalModes, uint>();

            termkvp.Add(TerminalModes.ECHO, 53);

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

            if (IsRoot)
            {
                SwitchToRoot(decryptedPassword, shellStream);
            }

            WriteStream(Command, shellStream);
            var result = ReadStream(shellStream);

            _log.Information(result);

            _log.Success("Command Execute finished!");
            client.Disconnect();
            return(true);
        }
Beispiel #24
0
        public void ExeSSH(Object s)
        {
            using (var conninfo = new PasswordConnectionInfo(ip, log, pass))
            {
                //  try

                Renci.SshNet.SshClient client = new Renci.SshNet.SshClient(conninfo);

                //  conninfo.Timeout = TimeSpan.FromSeconds(50);
                try
                {
                    client.Connect();
                }
                catch (Exception ex)
                {
                }
                try
                {
                    Renci.SshNet.ShellStream stream = client.CreateShellStream("ssh", 180, 324, 1800, 3600, 8000);
                    foreach (string command in list)
                    {
                        stream.Write(command + "\n");
                        System.Threading.Thread.Sleep(5000);
                        string temp_string = stream.Read();
                        //    File.WriteAllText(path, temp_string, Encoding.UTF8);
                        File.WriteAllText("C:/" + ip + ".txt", temp_string, Encoding.UTF8);
                        System.Threading.Thread.Sleep(5000);
                    }
                    client.Disconnect();
                }
                catch (Exception ex)
                {
                }
            }
        }
Beispiel #25
0
    public void ConnectionTests(int count, int pause)
    {
        var regex = new Regex(@"^\d+\s[\d\w:]+\s[\d\.]+\s.+?\s.+?$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline);

        Renci.SshNet.SshClient client;
        {
            var path = Concrete.Client.FixPath(_config.PathToPrivateKey !);
            using var keyFile = new Renci.SshNet.PrivateKeyFile(path);
            client            = new Renci.SshNet.SshClient(_config.Host, _config.Port, _config.Username, keyFile);
        }

        client.Connect();

        while (count-- > 0)
        {
            string output;
            {
                using var command      = client.CreateCommand("cat /tmp/dhcp.leases", Encoding.UTF8);
                command.CommandTimeout = TimeSpan.FromSeconds(1);
                output = command.Execute();
            }

            Assert.NotNull(output);
            Assert.NotEmpty(output);
            Assert.Matches(regex, output);

            Thread.Sleep(pause);
        }

        client.Disconnect();
        client.Dispose();
    }
Beispiel #26
0
        private static void connectSSH(SshClient client)
        {
            ConsoleLogStartAction(Resources.UILogging.ConnectSSH);

            client.Connect();

            ConsoleEndAction();
        }
 /// <summary>
 /// Init SSH client.
 /// </summary>
 private void InitClient()
 {
     _client = new Renci.SshNet.SshClient(_connectionInfo)
     {
         KeepAliveInterval = new TimeSpan(0, 0, 30),
         ConnectionInfo    = { Timeout = new TimeSpan(0, 0, 20) }
     };
 }
Beispiel #28
0
        public SshManager(string remoteIp, string username, string password, bool autoConnect = false)
        {
            sshClient = new SshClient(remoteIp, username, password);
            scpClient = new ScpClient(remoteIp, username, password);

            if (autoConnect)
                Connect();
        }
        /// <summary>
        /// Open a Connection to the cloudera
        /// </summary> 
        private void OpenConnecion()
        {
            sshClient = new SshClient(hostname, userName, password);
            sshClient.Connect();

            scpClient = new ScpClient(hostname, userName, password);
            scpClient.Connect();
        }
Beispiel #30
0
 public Uploader(TargetProfile p)
 {
     Ip = p.IpAddress.ToString();
     UserName = p.Login;
     var password = p.Pass.ToString(); //TODO: remove vulnerability breach 
     _scpClient = new ScpClient(Ip, UserName, password);
     _sshClient = new SshClient(Ip, UserName, password);
 }
Beispiel #31
0
        // TODO: DO SOME CHECKS FOR NULLS ETC AND IF THE METHODS WILL THROW ERRORS ETC IF CALLED IN THE WRONG ORDER!!!
        public SSHController(string address, string username, string password)
        {
            _address = address;
            _username = username;
            _password = password;

            _client = new SshClient(_address, _username, _password);
        }
Beispiel #32
0
        public Client2(string host, string username, string password)
        {
            this.Host = host;
            this.UserName = username;
            this.Password = password;

            sshClient = new SshClient(host, username, password);
        }
Beispiel #33
0
        public FormEditor(String configuration, SshClient connection)
        {
            _connection = connection;
            InitializeComponent();
            Text = connection.ConnectionInfo.Host + " - "+ Text;

            backgroundWorkerConnect.RunWorkerAsync(configuration);
        }
Beispiel #34
0
        public Client2(string host, string username, string password)
        {
            this.Host     = host;
            this.UserName = username;
            this.Password = password;

            sshClient = new SshClient(host, username, password);
        }
Beispiel #35
0
 private void Connect()
 {
     if (_connected) return;
     _client = new SshClient(_con);
     _client.Connect();
     _ports = new List<ForwardedPortLocal>();
     _connected = true;
 }
Beispiel #36
0
 /// <summary>
 /// Represents instance of the SSH shell object.
 /// </summary>
 /// <param name="sshClient">The SSH client.</param>
 /// <param name="input">The input.</param>
 /// <param name="output">The output.</param>
 /// <param name="extendedOutput">The extended output.</param>
 /// <param name="terminalName">Name of the terminal.</param>
 /// <param name="columns">The columns.</param>
 /// <param name="rows">The rows.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="bufferSize">Size of the buffer for output stream.</param>
 internal SshShell(Renci.SshNet.SshClient sshClient, Stream input, Stream output, Stream extendedOutput,
                   string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize)
 {
     _sshShell           = sshClient.CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, null, bufferSize);
     _sshShell.Starting += _sshShell_Starting;
     _sshShell.Started  += _sshShell_Started;
     _sshShell.Stopping += _sshShell_Stopping;
     _sshShell.Stopped  += _sshShell_Stopped;
 }
        public static String getPath(String username, String password, String host)
        {
            var ssh = new Renci.SshNet.SshClient(host, username, password);

            try
            {
                ssh.Connect();
            }
            catch (Exception error)
            {
                Console.WriteLine("Couldn't connect to iPhone");
            }

            if (ssh.IsConnected)
            {
                Console.WriteLine("\nConnected to iPhone (" + host + ")");
            }

            else
            {
                Console.WriteLine("Could't connect to iPhone");
            }

            Console.WriteLine("\nfind /var/mobile/Containers -iname pw.dat");
            var cmd    = ssh.CreateCommand("find /var/mobile/Containers -iname pw.dat");            //  very long list
            var asynch = cmd.BeginExecute(delegate(IAsyncResult ar)
            {
                Console.WriteLine("\nDisconnected from iPhone.");
            }, null);

            var reader = new StreamReader(cmd.OutputStream);

            String output = "";

            while (!asynch.IsCompleted)
            {
                var result = reader.ReadToEnd();
                if (string.IsNullOrEmpty(result))
                {
                    continue;
                }
                Console.Write("\n> " + result);
                output = result;
            }
            cmd.EndExecute(asynch);

            String path = output.Substring(0, 76);

            Console.WriteLine(path);


            reader.Close();
            ssh.Disconnect();


            return(path);
        }
Beispiel #38
0
        public void button1_Click(object sender, EventArgs e)
        {
            int port = int.Parse(userInputPort.Text);

            //Renci.SshNet.SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
            try
            {
                cSSH = new SshClient(userInputIP.Text, port, userInputUsername.Text, userInputPassword.Text);
            }
            catch (Exception ex)
            {
                printError(ex.ToString() + " happened in Renci.SshNet.SshClient");
                return;
            }


            try
            {
                cSSH.Connect();
            }

            catch (Exception ex)
            {
                printError(ex.ToString() + " happened in cSSH.Connect()");
                return;
            }

            if (connected == true)
            {
                //disconnect
                statusLabel.ForeColor = Color.Red;
                statusLabel.Text      = "Disconnected";
                printInfo("Disconnected by user.");
                connected          = false;
                buttonConnect.Text = "Connect to device";
                cSSH.Disconnect();
                cSSH.Dispose();
                return;
            }

            if (connected == false)
            {
                //connect
                statusLabel.ForeColor = Color.DarkGreen;
                statusLabel.Text      = "Connected";
                printInfo("Successfully connected.");
                connected          = true;
                buttonConnect.Text = "Disconnect from device";
            }
        }
Beispiel #39
0
        private void btn_Q1_Click(object sender, EventArgs e)
        {
            Renci.SshNet.SshClient _session = new Renci.SshNet.SshClient(txt_ip1.Text, txt_user1.Text, txt_pwd1.Text);

            SshCommand x = sshC.RunCommand(txt_cmd1.Text);

            //SshCommand z2 = sshC.RunCommand(txt_cmd1.Text);
            //string z1 = z2.Execute(txt_cmd1.Text);

            txt_Show1.Text = "结果信息\n" + x.Result + "错误信息:" + x.Error;

            // txt_Show1.Text += "错误信息\n" + x.Error;
            //txt_Show1.Text += z1;
        }
Beispiel #40
0
        /// <summary>
        /// 初期化
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="userName"></param>
        /// <param name="userPasword"></param>
        protected override void Initialization(string host, int port, string userName, string userPasword)
        {
            // 基底クラス初期化
            base.Initialization(host, port, userName, userPasword);

            // 認証情報生成
            this.m_AuthenticationMethodList.Add(new PasswordAuthenticationMethod(userName, userPasword)
            {
            });

            // 接続情報生成
            this.m_ConnectionInfo = new ConnectionInfo(host, port, userName, this.m_AuthenticationMethodList.ToArray());

            // SSHクライアントオブジェクト生成
            this.m_Client = new Renci.SshNet.SshClient(this.m_ConnectionInfo);
        }
Beispiel #41
0
        private void btn_C1_Click(object sender, EventArgs e)
        {
            sshC = new SshClient(txt_ip1.Text, txt_user1.Text, txt_pwd1.Text);

            sshC.Connect();


            if (sshC.IsConnected)
            {
                lab_ContentState1.Text = "连接状态:成功";
            }
            else
            {
                lab_ContentState1.Text = "连接状态:失败";
            }
        }
Beispiel #42
0
        private string SshExec(ResourceNode node, string command, string args = "")
        {
            lock (_lock)
            {
                int    sshResult  = 0;
                string sshOut     = "";
                string sshErr     = "";
                string sshCommand = command + " " + args;

                var sshExec = new Ssh2
                              .SshClient(node.NodeAddress, node.Credentials.Username, node.Credentials.Password);
                //.SshExec(node.NodeAddress, node.Credentials.Username, node.Credentials.Password);

                try
                {
                    sshExec.Connect();
                    //sshResult = sshExec.RunCommand(sshCommand, ref sshOut, ref sshErr);
                    var ssh = sshExec.RunCommand(sshCommand);
                    ssh.Execute();

                    sshResult = ssh.ExitStatus;
                    sshErr    = ssh.Error;
                    sshOut    = ssh.Result;
                }
                catch (Exception e)
                {
                    Log.Warn(e.Message);
                    throw;
                }
                finally
                {
                    if (sshExec.IsConnected)
                    {
                        sshExec.Disconnect();
                    }
                }

                sshErr = sshErr.Replace('.', ' '); // Cert creation emits many dots
                if (!String.IsNullOrWhiteSpace(sshErr))
                {
                    throw new Exception(String.Format("Ssh execution error. Command: \"{0}\". Code: {1}, StdOut: {2}, StdErr: {3}", sshCommand, sshResult, sshOut, sshErr));
                }

                return(sshOut);
            }
        }
        private void InternalConnect(string host, int port, string username, string password, string workingDirectory)
        {
            if (_isConnected)
            {
                // Change the working directory only if we use ScpClient.
                if (_scpClient != null)
                {
                    ChangeWorkingDirectory(workingDirectory);
                }
                return;
            }

            // Restart timer
            _stopWatch.Restart();
            _lastElapsedMilliseconds = 0;

            // Start connection ...
            PrintTime($"Connecting to {username}@{host}:{port} ...");

            _sshClient = new SshClient(host, port, username, password);
            _sshClient.Connect();

            try
            {
                // Use SFTP for file transfers
                var sftpClient = new SftpClient(host, port, username, password);
                sftpClient.Connect();
                _sftpClient = sftpClient;
            }
            catch (Exception ex)
            {
                // Use SCP if SFTP fails
                PrintTime($"Error: {ex.Message} Is SFTP supported for {username}@{host}:{port}? We are using SCP instead!");
                _scpClient = new ScpClient(host, port, username, password);
                _scpClient.Connect();
            }

            var _connectionInfo = _sshClient.ConnectionInfo;

            PrintTime($"Connected to {_connectionInfo.Username}@{_connectionInfo.Host}:{_connectionInfo.Port} via SSH and {(_sftpClient != null ? "SFTP" : "SCP")}");

            _isConnected = true;

            ChangeWorkingDirectory(workingDirectory);
        }
        public SshStream(Session session)
        {
            this.session = session;

            var connectionService = session.GetService <ConnectionService>();

            var channel = connectionService.AddChannel();

            string clientAddress = ((IPEndPoint)this.session.RemoteEndPoint).Address.MapToIPv4().ToString();
            uint   clientPort    = (uint)((IPEndPoint)this.session.RemoteEndPoint).Port;

            this.session.SendMessage(new ForwardedTcpipMessage(channel.ServerChannelId, channel.ClientInitialWindowSize,
                                                               channel.ClientMaxPacketSize, connectionService.ForwardAddress,
                                                               connectionService.ForwardPort, clientAddress, clientPort));

            this.client = new Renci.SshNet.SshClient(clientAddress, 22, this.session.Username, "password");
            this.client.Connect();
        }
Beispiel #45
0
        public List <CommandResult> ExecuteCommands(List <string> commands, ILog log)
        {
            var results = new List <CommandResult>();

            var connectionInfo = GetConnectionInfo(_config);

            using (var ssh = new Renci.SshNet.SshClient(connectionInfo))
            {
                try
                {
                    ssh.Connect();

                    foreach (var command in commands)
                    {
                        try
                        {
                            var cmd = ssh.RunCommand(command);

                            results.Add(new CommandResult {
                                Command = command, Result = cmd.Result, IsError = false
                            });
                        }
                        catch (Exception exp)
                        {
                            results.Add(new CommandResult {
                                Command = command, Result = exp.ToString(), IsError = true
                            });
                            break;
                        }
                    }

                    ssh.Disconnect();
                }
                catch (Exception e)
                {
                    log?.Error($"SShClient :: Error executing command {e}");
                }
            }

            return(results);
        }
Beispiel #46
0
    public Client(IOptions <Config> options)
    {
        var config = Guard.Argument(options).NotNull().Wrap(o => o.Value).NotNull().Value;

        if (!string.IsNullOrWhiteSpace(config.Password))
        {
            _sshClient = new(config.Host, config.Port, config.Username, config.Password);
        }
        else if (!string.IsNullOrWhiteSpace(config.PathToPrivateKey))
        {
            var path = FixPath(config.PathToPrivateKey);
            var privateKeyFileInfo = new FileInfo(path);
            using var stream         = privateKeyFileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
            using var privateKeyFile = new Renci.SshNet.PrivateKeyFile(stream);
            _sshClient = new(config.Host, config.Port, config.Username, privateKeyFile);
        }
        else
        {
            _sshClient = new(config.Host, config.Port, config.Username);
        }
    }
Beispiel #47
0
 public void ExSSH(string ip, string log, string pass, List <String> list)
 {
     //     foreach (string ipadd in ip)
     //     {
     using (var conninfo = new PasswordConnectionInfo(ip, log, pass))
     {
         Renci.SshNet.SshClient client = new Renci.SshNet.SshClient(conninfo);
         client.Connect();
         Renci.SshNet.ShellStream stream = client.CreateShellStream("ssh", 180, 324, 1800, 3600, 8000);
         foreach (string command in list)
         {
             // var command = "show config modified";
             stream.Write(command + "\n");
             System.Threading.Thread.Sleep(10000);
             string temp_string = stream.Read();
             //  Console.Write(temp_string);
             File.WriteAllText("C:/" + ip + " thread n- " + System.Threading.Thread.CurrentThread.ManagedThreadId + ".txt", temp_string, Encoding.UTF8);
             //     System.Threading.Thread.Sleep(5000);
         }
         client.Disconnect();
         //   }
     }
 }
Beispiel #48
0
        /// <summary>
        /// Secure shell host client.
        /// </summary>
        /// <param name="sshConnection">SSH connection adapter.</param>
        public SshClient(SshConnection sshConnection)
        {
            _sshConnection = sshConnection;

            // Get the authentication used.
            if (sshConnection.IsPrivateKeyAuthentication)
            {
                // Add the private key files.
                List <Renci.SshNet.PrivateKeyFile> privateKeyFile = new List <Renci.SshNet.PrivateKeyFile>();
                foreach (PrivateKeyFile keyFile in sshConnection.PrivateKeyFiles)
                {
                    privateKeyFile.Add(keyFile.SshNetPrivateKeyFile);
                }

                // If port number is 22 (default).
                if (sshConnection.Port == 22)
                {
                    _sshClient = new Renci.SshNet.SshClient(sshConnection.Host, sshConnection.Username, privateKeyFile.ToArray());
                }
                else
                {
                    _sshClient = new Renci.SshNet.SshClient(sshConnection.Host, sshConnection.Port, sshConnection.Username, privateKeyFile.ToArray());
                }
            }
            else
            {
                // If port number is 22 (default).
                if (sshConnection.Port == 22)
                {
                    _sshClient = new Renci.SshNet.SshClient(sshConnection.Host, sshConnection.Username, sshConnection.Password);
                }
                else
                {
                    _sshClient = new Renci.SshNet.SshClient(sshConnection.Host, sshConnection.Port, sshConnection.Username, sshConnection.Password);
                }
            }
        }
Beispiel #49
0
        private void btn_C2_Click(object sender, EventArgs e)
        {
            /*
             * Resources.HOST 192.168.10.131
             * Resources.PORT 22
             * Resources.USERNAME root
             * proxyHost
             * Resources.PORT
             * Resources.USERNAME
             * Resources.PASSWORD
             * Resources.USERNAME
             */
            var connectionInfo = new ConnectionInfo("10.69.66.67", 22, "toor4nsn",
                                                    ProxyTypes.None, "192.168.253.18", 22, "toor4nsn", "oZPS0POrRieRtu",
                                                    new KeyboardInteractiveAuthenticationMethod("10.69.66.67"));


            Renci.SshNet.SshClient _session2 = new Renci.SshNet.SshClient(connectionInfo);
            _session2.Connect();
            _session2.RunCommand("lst");

            //Renci.SshNet.Session zz = new Renci.SshNet.Session(,);
            //xx.Start();
        }
Beispiel #50
0
        private void btn_Q2_Click(object sender, EventArgs e)
        {
            sshC = new SshClient("192.168.10.131", "root", "123123");

            sshC.KeepAliveInterval      = new TimeSpan(0, 0, 30);
            sshC.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20);
            sshC.Connect();

            // 动态链接
            ForwardedPortDynamic port = new ForwardedPortDynamic("127.0.0.1", 22);

            sshC.AddForwardedPort(port);
            port.Start();

            ////var fport = new ForwardedPortRemote("192.168.10.131", 22, "127.0.0.1", 22);
            ////sshC.AddForwardedPort(fport);
            ////fport.Start();

            ////string x = sshC.RunCommand("pwd").Result;
            ;
            string x = sshC.RunCommand("pwd").Result;

            ;
        }
Beispiel #51
0
        public SshClient(object options)
        {
            BlendedJSEngine.Clients.Value.Add(this);
            var host       = options.GetProperty("host").ToStringOrDefault();
            var port       = options.GetProperty("port").ToIntOrDefault(22);
            var user       = options.GetProperty("user").ToStringOrDefault();
            var password   = options.GetProperty("password").ToStringOrDefault();
            var privateKey = options.GetProperty("privateKey").ToStringOrDefault();

            if (string.IsNullOrEmpty(privateKey) == false)
            {
                byte[]         primateKeyBytes = Encoding.UTF8.GetBytes(privateKey);
                PrivateKeyFile primateKeyFile  = new PrivateKeyFile(new MemoryStream(primateKeyBytes));
                var            connectionInfo  = new Renci.SshNet.ConnectionInfo(host, port, user,
                                                                                 new PrivateKeyAuthenticationMethod(user, primateKeyFile));
                _client = new Renci.SshNet.SshClient(connectionInfo);
            }
            else
            {
                var connectionInfo = new Renci.SshNet.ConnectionInfo(host, port, user,
                                                                     new PasswordAuthenticationMethod(user, password));
                _client = new Renci.SshNet.SshClient(connectionInfo);
            }
        }
Beispiel #52
0
 public LibraryAsyncTests(LibraryFixture libraryFixture)
 {
     _sut = libraryFixture.Library;
 }
        private void btnUnixDetect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var KeyboardInteractive = new Ssh.KeyboardInteractiveAuthenticationMethod(Host.Username);
                var Password            = new Ssh.PasswordAuthenticationMethod(Host.Username, AES.DecryptString(Host.Password));
                var encryptedPassword   = Host.Password;
                KeyboardInteractive.AuthenticationPrompt += delegate(object sender1, Ssh.Common.AuthenticationPromptEventArgs e1)
                {
                    foreach (var prompt in e1.Prompts)
                    {
                        if (prompt.Request.ToLower().Contains("password"))
                        {
                            prompt.Response = AES.DecryptString(encryptedPassword);
                        }
                    }
                };
                var conn = new Ssh.ConnectionInfo(Host.Value,
                                                  Host.Username,
                                                  Password,
                                                  KeyboardInteractive);
                using (Ssh.SshClient client = new Ssh.SshClient(conn))
                {
                    client.Connect();
                    var termdic = new Dictionary <Ssh.Common.TerminalModes, uint>();
                    termdic.Add(Ssh.Common.TerminalModes.ECHO, 0);

                    using (var shell = client.CreateShellStream("gogrid", 80, 24, 800, 600, 1024, termdic))
                    {
                        using (var output = new StreamReader(shell))
                            using (var input = new StreamWriter(shell))
                            {
                                input.AutoFlush = true;
                                while (shell.Length == 0)
                                {
                                    Thread.Sleep(500);
                                }
                                //shell.WriteLine("stty raw -echo"); // disable echo
                                while (shell.Length != 0)
                                {
                                    shell.Read();
                                }
                                shell.Write("([ -d ~/oraInventory/ContentsXML/ ] && [ -e ~/oraInventory/ContentsXML/inventory.xml ])  && echo epmi1 || echo epmi0\n");
                                while (shell.Length == 0)
                                {
                                    Thread.Sleep(500);
                                }
                                var resp = shell.ReadLine();
                                while (shell.Length != 0)
                                {
                                    shell.Read();
                                }
                                if (System.Text.RegularExpressions.Regex.IsMatch(resp, "epmi1$"))
                                {
                                    shell.Write("cat ~/oraInventory/ContentsXML/inventory.xml\n");
                                    while (shell.Length == 0)
                                    {
                                        Thread.Sleep(500);
                                    }
                                    resp = Read(output, true);
                                    XmlDocument doc = new XmlDocument();
                                    doc.LoadXml(resp);
                                    var nodes = doc.SelectNodes("INVENTORY/HOME_LIST/HOME");
                                    for (int i = 0; i < nodes.Count; i++)
                                    {
                                        if (Regex.IsMatch(nodes[i].Attributes["NAME"].Value, @"EpmSystem_\S+"))
                                        {
                                            tbxUnixPath.Text = nodes[i].Attributes["LOC"].Value;
                                            break;
                                        }
                                    }
                                    MessageBox.Show("Success");
                                }
                            }
                    }
                    client.Disconnect();
                }
            }
            catch (Ssh.Common.SshAuthenticationException)
            {
                MessageBox.Show("Failed to authenticate to server. Check username and password.");
            }
            catch (Exception)
            {
                MessageBox.Show("Unknown error.");
            }
        }
Beispiel #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SshCommand"/> class.
 /// </summary>
 /// <param name="sshClient">The SSH client.</param>
 /// <param name="commandText">The command text.</param>
 /// <exception cref="ArgumentNullException">Either <paramref name="commandText"/> is null.</exception>
 internal SshCommand(Renci.SshNet.SshClient sshClient, string commandText)
 {
     _sshCommand = sshClient.CreateCommand(commandText);
 }
Beispiel #55
0
 public void sshConnect()
 {
     ssh = new SshClient(connectionInfo);
     ssh.Connect();
 }
Beispiel #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SshCommand"/> class.
 /// </summary>
 /// <param name="sshClient">The SSH client.</param>
 /// <param name="commandText">The command text.</param>
 /// <param name="encoding">The encoding to use for the results.</param>
 /// <exception cref="ArgumentNullException">Either <paramref name="commandText"/> is null.</exception>
 internal SshCommand(Renci.SshNet.SshClient sshClient, string commandText, Encoding encoding)
 {
     _sshCommand = sshClient.CreateCommand(commandText, encoding);
 }
Beispiel #57
-1
        /// <summary>
        /// Perform some kind of control action
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            bool success = false;
            try
            {
                var sourcePath = Path.Combine(Globals.CacheFolder, SourceFile);
                if(!File.Exists(sourcePath))
                {
                    Logger.Warn("SourceFile '" + sourcePath + "' does not exist");
                    return false;
                }

                var sourceText = File.ReadAllText(sourcePath);

                var displayText = ScriptHelpers.ReplaceVars(sourceText);

                var displayPath = Path.Combine(Globals.CacheFolder,
                                               Globals.CustomerSerialNumber + DateTime.Now.Ticks + ".tmp");
                
                File.WriteAllText(displayPath, displayText);

                Process.Start("notepad", displayPath);

            }
            catch (Exception e)
            {
                Logger.Warn("Exception in report command: " + e.Message);
            }
            return success;
        }
Beispiel #58
-2
    static void Main(string[] args)
    {
        // Setup Credentials and Server Information
        ConnectionInfo ConnNfo = new ConnectionInfo("dan.hangone.co.za", 224, "Dan",
            new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("Dan","letmein5")/*,

                // Key Based Authentication (using keys in OpenSSH Format)
                new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{
                    new PrivateKeyFile(@"..\openssh.key","passphrase")
                }),*/
            }
        );
        /*
        // Execute a (SHELL) Command - prepare upload directory
        using (var sshclient = new SshClient(ConnNfo))
        {
            sshclient.Connect();
            using (var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest"))
            {
                cmd.Execute();
                Console.WriteLine("Command>" + cmd.CommandText);
                Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
            }
            sshclient.Disconnect();
        }
        */

        /*
        // Upload A File
        using (var sftp = new SftpClient(ConnNfo))
        {
            string uploadfn = "Renci.SshNet.dll";

            sftp.Connect();
            sftp.ChangeDirectory("/tmp/uploadtest");
            using (var uplfileStream = System.IO.File.OpenRead(uploadfn))
            {
                sftp.UploadFile(uplfileStream, uploadfn, true);
            }
            sftp.Disconnect();
        }
        */
        // Execute (SHELL) Commands
        using (var sshclient = new SshClient(ConnNfo))
        {
            sshclient.Connect();

            // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
            Console.WriteLine(sshclient.CreateCommand("/log print").Execute());
            Console.WriteLine(sshclient.CreateCommand("/int print").Execute());
            Console.WriteLine(sshclient.CreateCommand("/ppp secret print").Execute());
            sshclient.Disconnect();
        }
        Console.ReadKey();
    }