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


C# SshClient.Disconnect方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例5: 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

示例6: run

 public void run(string host, string user, string pass, string command)
 {
     using (var sshClient = new SshClient(host, user, pass))
     {
         sshClient.Connect();
         sshClient.RunCommand(command);
         sshClient.Disconnect();
         sshClient.Dispose();
     }
 }
开发者ID:bobcowher,项目名称:SystemRemote1.0,代码行数:10,代码来源:Form1.cs

示例7: connBtn_Click

        private void connBtn_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                sshconn = true;
                try
                {
                    using (var client = new SshClient(hostTxt.Text, uidTxt.Text, passwordTxt.Text))
                    {
                        client.Connect();
                        client.Disconnect();
                        MessageBox.Show("logged in!");
                    }
                    LuiceEditor editor = new LuiceEditor(this);
                    editor.Show();
                }
                catch
                {
                    MessageBox.Show("error: check again the data that you inserted and retry.");
                }
            }
            else
            {
                sshconn = false;
                string connection1 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + authTxt.Text + ";UID=" + uidTxt.Text + ";Password=" + passwordTxt.Text + ";";
                string connection2 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + charTxt.Text + ";UID=" + uidTxt.Text + ";Password=" + passwordTxt.Text + ";";
                string connection3 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + worldTxt.Text + ";UID=" + uidTxt.Text + ";Password=" + passwordTxt.Text + ";";
                MySqlConnection conn1 = new MySqlConnection(connection1);
                MySqlConnection conn2 = new MySqlConnection(connection2);
                MySqlConnection conn3 = new MySqlConnection(connection3);

                try
                {
                    //this is needed only to check if inserted data is correct
                    conn1.Open();
                    conn2.Open();
                    conn3.Open();
                    //closing test connections
                    conn1.Close();
                    conn2.Close();
                    conn3.Close();
                    MessageBox.Show("logged in!");
                    //passing method from form1 to LuiceEditor Form
                    LuiceEditor editor = new LuiceEditor(this);
                    editor.Show();
                }
                catch
                {
                    MessageBox.Show("error: check again the data that you inserted and retry.");
                }
                
            }
            
        }
开发者ID:GlassFace,项目名称:Luice,代码行数:54,代码来源:Form1.cs

示例8: _main

        static void _main()
        {
            BlackCore.basic.cParams args = bcore.app.args;

               client = new System.Net.Sockets.TcpClient();

               int wavInDevices = WaveIn.DeviceCount;
               int selWav = 0;
               for (int wavDevice = 0; wavDevice < wavInDevices; wavDevice++)
               {
               WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(wavDevice);
               Console.WriteLine("Device {0}: {1}, {2} channels", wavDevice, deviceInfo.ProductName, deviceInfo.Channels);
               }

               Console.Write("Select device: ");
               selWav = int.Parse(Console.ReadLine());
               Console.WriteLine("Selected device is " + selWav.ToString());

               sshClient = new SshClient(args["host"], args["user"], args["pass"]);
               sshClient.Connect();

               if (sshClient.IsConnected)
               {

               shell = sshClient.CreateShellStream("xterm", 50, 50, 640, 480, 17640);
               Console.WriteLine("Open listening socket...");
               shell.WriteLine("nc -l " + args["port"] + "|pacat --playback");
               System.Threading.Thread.Sleep(2000);

               Console.WriteLine("Try to connect...");
               client.Connect(args["host"], int.Parse(args["port"]));
               if (!client.Connected) return;
               upStream = client.GetStream();

               //====================

               WaveInEvent wavInStream = new WaveInEvent();
               wavInStream.DataAvailable += new EventHandler<WaveInEventArgs>(wavInStream_DataAvailable);
               wavInStream.DeviceNumber = selWav;
               wavInStream.WaveFormat = new WaveFormat(44100, 16, 2);
               wavInStream.StartRecording();
               Console.WriteLine("Working.....");

               Console.ReadKey();
               sshClient.Disconnect();
               client.Close();
               wavInStream.StopRecording();
               wavInStream.Dispose();
               wavInStream = null;
               }
        }
开发者ID:hapylestat,项目名称:StreamAudio,代码行数:51,代码来源:Program.cs

示例9: Main

        static void Main(string[] args)
        {
            string servers = ConfigurationManager.AppSettings["servers"];
            string username = ConfigurationManager.AppSettings["username"];
            string password = ConfigurationManager.AppSettings["password"];
            foreach (string server in servers.Split(','))
            {
                ConnectionInfo ConnNfo = new ConnectionInfo(server, 22, username,
                    new AuthenticationMethod[]{
                        // Pasword based Authentication
                        new PasswordAuthenticationMethod(username,password)
                    }
                    );

                string[] items = { "active_pwr", "energy_sum", "v_rms", "pf","enabled" };

                using (var sshclient = new SshClient(ConnNfo))
                {
                    Console.WriteLine("Connecting to {0}", server);
                    sshclient.Connect();
                    // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
                    foreach (string itemName in items)
                    {
                        for (int port = 1; port < 7; port++)
                        {
                            string outputFileName = string.Format("{0}-{1}-{2}.txt", server, itemName, port);
                            Console.WriteLine(string.Format("{0}{1}", itemName, port));
                            string result = sshclient.CreateCommand(string.Format("cat /proc/power/{0}{1}", itemName, port)).Execute();
                            if (!File.Exists(outputFileName))
                            {
                                using (var writer = File.CreateText(outputFileName))
                                {
                                    writer.WriteLine(string.Format("{0}, {1}", DateTime.Now.Ticks, result));
                                }
                            }
                            else
                            {
                                using (var writer = File.AppendText(outputFileName))
                                {
                                    writer.WriteLine(string.Format("{0}, {1}", DateTime.Now.Ticks, result));
                                }
                            }
                            Console.WriteLine(result);
                        }
                    }
                    sshclient.Disconnect();
                }
            }
        }
开发者ID:tiernano,项目名称:ubntmpowerreader,代码行数:49,代码来源:Program.cs

示例10: Bootstrap

        public object Bootstrap(Drone drone)
        {
            using (var ssh = new SshClient(ChefHost, "root", "0953acb"))
            {
                ssh.Connect();
                var cmd = ssh.RunCommand(string.Format("knife bootstrap {0} -x root -P 0953acb --sudo -N {1} --run-list speedymailer-drone -E xomixfuture", drone.Id, Guid.NewGuid().ToString().Replace("-", "")));   //  very long list
                ssh.Disconnect();

                return new
                {
                    Drone = drone,
                    Data = cmd.Result.Replace("\n", "<br>")
                };
            }
        }
开发者ID:mamluka,项目名称:SpeedyMailer,代码行数:15,代码来源:DronesController.cs

示例11: returnSSHFrom

        //Same as returnSSH, but specific a specific server isntead of a the generic RPI server
        public string returnSSHFrom(string passedCommand, string passedServer)
        {
            SshClient AuthClient = new SshClient(passedServer, username, password);

            try
            {
                AuthClient.Connect();
                SshCommand RunCommand = AuthClient.RunCommand(passedCommand);
                AuthClient.Disconnect();
                return RunCommand.Result;
            }
            catch
            {
                return "";
            }
        }
开发者ID:daberkow,项目名称:RPI_Helpdesk_pstat,代码行数:17,代码来源:RPI_Auth.cs

示例12: returnSSH

        private string username = ""; //private store for username and password

        #endregion Fields

        #region Methods

        //Use stored infor to run comamnds on a server
        public string returnSSH(string passedCommand)
        {
            SshClient AuthClient = new SshClient("rcs.rpi.edu", username, password);

            try
            {
                AuthClient.Connect();
                SshCommand RunCommand = AuthClient.RunCommand(passedCommand);
                AuthClient.Disconnect();
                return RunCommand.Result;
            }
            catch
            {
                return "";
            }
        }
开发者ID:daberkow,项目名称:RPI_Helpdesk_pstat,代码行数:23,代码来源:RPI_Auth.cs

示例13: rpi_authent

        //Authenticate users
        public bool rpi_authent(string passedUsername, string passedPassword)
        {
            SshClient AuthClient = new SshClient("rcs.rpi.edu", passedUsername, passedPassword);//Using Renci

            try
            {
                AuthClient.Connect();       //try to connect
                AuthClient.Disconnect();    //If that worked disconnect
                AuthClient.Dispose();       //Clean up connection
                username = passedUsername;  //Store data in private collection because it worked
                password = passedPassword;
                return true;
            }
            catch {
                return false;               //This failed, either server is bad, but thats public so username and password are bad
            }
        }
开发者ID:daberkow,项目名称:RPI_Helpdesk_pstat,代码行数:18,代码来源:RPI_Auth.cs

示例14: RebootButton_Click

 protected void RebootButton_Click(object sender, EventArgs e)
 {
     try
     {
         using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s"))
         {
             client.Connect();
             client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./RightAlertRemoteRebootIssued-SQL"); // SSH Command Here
             client.RunCommand("sudo reboot"); // SSH Command Here
             client.Disconnect();
         }
     }
     catch (Exception ex)
     {
         Response.Redirect("Down.html");
     }
 }
开发者ID:sbobhate,项目名称:Right-Alert,代码行数:17,代码来源:Alerts.aspx.cs

示例15: ExecuteCommand

 //выполнение команды
 public override void ExecuteCommand(string command)
 {
     try
     {
         using (var sshclient = new SshClient(connInfo))
         {
             sshclient.Connect();                  
             Execute(sshclient, command);
             sshclient.Disconnect();
         }
         _success = true;
     }
     catch (Exception ex)//заменить на проброс исключения
     {
         _success = false;
         _listError.Add(ex.Message);
     }
 }
开发者ID:DaurenAmanbayev,项目名称:RemoteWork,代码行数:19,代码来源:SshExpect.cs


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