C# SSH類


先引用Renci.SshNet   https://github.com/sshnet/SSH.NET

另一個例子 https://www.cnblogs.com/DerekDeng/p/12126567.html

using System;
using System.IO;
using Renci.SshNet;
using Renci.SshNet.Sftp;

namespace SSHTest
{
    public class SshHelper
    {
        public static string _host;
        public static string _username;
        public static string _password;
        public static int _port = 22;
        public static string _command;

        public static string _serverdir = "/tmp/";
        public static string _clientdir = @"D:\";
        public static string _filename = "測試表.csv";
        
        public static ConnectionInfo CreateConnectionInfo(string _host, int _port, string _username)
        {
            //安裝憑據和服務器信息
            ConnectionInfo WeiConnInfo = new ConnectionInfo(_host, _port, _username, new PasswordAuthenticationMethod(_username,_password));
            return WeiConnInfo;
        }

        /// <summary>
        /// 不依賴ConnectionInfo直接try連接並執行命令
        /// </summary>
        public void Start()
        {
            using (var client = new SshClient(_host, _username, _password))
            {
                try
                {
                    string command = _command;
                    client.Connect();
                    string result = client.RunCommand(command).Execute();
                    Console.WriteLine(result);
                    client.Disconnect();
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1.Message);
                }
            }

        }

        /// <summary>
        /// 執行 command
        /// </summary>
        public static void ExecuteCommand()
        {
            var WeiConnInfo = CreateConnectionInfo(_host, _port, _username);
            using (var sshclient = new SshClient(WeiConnInfo))
            {
                sshclient.Connect();
                using (var cmd = sshclient.CreateCommand(_command))
                {
                    string result = cmd.Execute();
                    Console.WriteLine("Command>" + cmd.CommandText);
                    Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
                    Console.WriteLine("result>" + result);
                }
                sshclient.Disconnect();
            }
        }


        /// <summary>
        /// 上傳
        /// </summary>
        public static void Upload()
        {
            var WeiConnInfo = CreateConnectionInfo(_host, _port, _username);
            using (var sftp = new SftpClient(WeiConnInfo))
            {
                string uploadfn = _clientdir + _filename;

                sftp.Connect();
                sftp.ChangeDirectory(_serverdir);
                using (var uplfileStream = System.IO.File.OpenRead(uploadfn))
                {
                    sftp.UploadFile(uplfileStream, _filename, true);
                }
                sftp.Disconnect();
            }
        }

        /// <summary>
        /// 下載
        /// </summary>
        public static void Download()
        {
            var WeiConnInfo = CreateConnectionInfo(_host, _port, _username);
            using (var sftp = new SftpClient(WeiConnInfo))
            {
                string downloadfn = _serverdir + _filename;
                sftp.Connect();

                string destinationPath = string.Format(@"{0}\{1}", _clientdir, _filename);
                //讀取server的SftpFileStream文件流
                using (SftpFileStream sftpStream = sftp.OpenRead(downloadfn))
                {
                    if (sftpStream.Length > 0)
                    {
                        //定義寫入本地的FileStream文件流
                        FileStream fileStream = File.Create(destinationPath, (int)sftpStream.Length);
                        //定義buffer大小200K
                        byte[] buffer = new byte[200 * 1024];
                        int count;
                        //每次讀取的buffer是200K,讀取的偏移量是0,實際讀取的長度
                        //每次吧實際讀取的長度賦值給count
                        //如果count<=0,終止讀取
                        //同時終止寫入
                        //偏移量0說明每次流讀或流寫的時候,讀過或寫過的就自動默認跳過了
                        while ((count = sftpStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fileStream.Write(buffer, 0, count);
                        }
                    }
                }
            }
        }
    }


    /// <summary>
    /// WeiSSH類使用示例
    /// </summary>
    public class SSHUse
    {
        public static void WeiSSHFuncUse()
        {
            SshHelper._host = "1.1.1.8";
            SshHelper._port = 22;
            SshHelper._username = "root";
            SshHelper._password = "830";

            SshHelper._command = "cd /tmp/; ls -lrt";
            SshHelper.ExecuteCommand();

            SshHelper._serverdir = "/tmp/";
            SshHelper._clientdir = @"D:\";
            SshHelper._filename = "測試表.csv";
            SshHelper.Upload();

            SshHelper._command = "mv /tmp/測試表.csv /tmp/測試表linux.csv";
            SshHelper.ExecuteCommand();

            SshHelper._serverdir = "/tmp/";
            SshHelper._clientdir = @"D:\";
            SshHelper._filename = "測試表linux.csv";
            SshHelper.Download();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM