当前位置: 首页>>代码示例>>C#>>正文


C# SshClient.Connect方法代码示例

本文整理汇总了C#中Renci.SshNet.SshClient.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# SshClient.Connect方法的具体用法?C# SshClient.Connect怎么用?C# SshClient.Connect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Renci.SshNet.SshClient的用法示例。


在下文中一共展示了SshClient.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: connect

        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);
            }
        }
开发者ID:fakusb,项目名称:FiVES-Nao-Visualisation,代码行数:26,代码来源:Program.cs

示例2: Main

    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();
    }
开发者ID:dagenes,项目名称:kubbe,代码行数:32,代码来源:Driver.cs

示例3: Main

    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();
    }
开发者ID:DanielHang,项目名称:Training,代码行数:58,代码来源:Program.cs

示例4: Main

        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();
        }
开发者ID:dagenes,项目名称:GitHubVS2013,代码行数:33,代码来源:Program.cs

示例5: ExecuteCommands

        //выполнение списка команд
        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);
            }

        }
开发者ID:DaurenAmanbayev,项目名称:RemoteWork,代码行数:32,代码来源:SshExpect.cs

示例6: LocalVmToolStripMenuItemClick

        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) ));
        }
开发者ID:mrdavidlaing,项目名称:wp-appliance-commander,代码行数:27,代码来源:Main.cs

示例7: ButtonConnectClick

        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;
        }
开发者ID:DynamicDevices,项目名称:dta,代码行数:25,代码来源:MainForm.cs

示例8: Run

        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;
        }
开发者ID:jbatonnet,项目名称:flowtomator,代码行数:26,代码来源:SshCommand.cs

示例9: ListenPort

        /// <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;
        }
开发者ID:sujathkumar,项目名称:legacypgs,代码行数:30,代码来源:SshListener.cs

示例10: GetUsers

        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;
                        }
                    }
                }
            }
        }
开发者ID:WWU-ACM,项目名称:NetworkFriendFinder,代码行数:35,代码来源:SshService.cs

示例11: Run

 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;
     }
 }
开发者ID:thayut,项目名称:MultiSessionTool2,代码行数:29,代码来源:RenziImpl.cs

示例12: DoSystemUniquePool

        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;
        }
开发者ID:bridgewell,项目名称:Hict,代码行数:32,代码来源:linuxhostinfo.cs

示例13: ExecuteCommand

        private static String ExecuteCommand(SshClient sshClient, String command)
        {
            if (!sshClient.IsConnected)
                sshClient.Connect();

            return sshClient.CreateCommand(command).Execute();
        }
开发者ID:JorgeHudson,项目名称:modSIC,代码行数:7,代码来源:SshExecExtensions.cs

示例14: button1_Click

        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());
        }
开发者ID:amolmore,项目名称:remotewget,代码行数:27,代码来源:RemoteWget.cs

示例15: SshFactory

 public SshFactory(String host, String username, String password)
 {
     _connection = new SshClient(host, username, password);
     _connection.Connect();
     _sftp = new SftpClient(_connection.ConnectionInfo);
     _sftp.Connect();
 }
开发者ID:a1binos,项目名称:SystemInteract.Net,代码行数:7,代码来源:SshFactory.cs


注:本文中的Renci.SshNet.SshClient.Connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。