SFTP客户端实现的三种办法

一、Renci.SshNet

首先添加下方库

创建类

using log4net;
using Renci.SshNet;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ftp
{
    public class SFTPHelper
    {
        #region 字段或属性

        private SftpClient sftp;
        /// <summary>
        /// SFTP连接状态
        /// </summary>
        public bool Connected { get { return sftp.IsConnected; } }
        #endregion

        #region 构造
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="user">用户名</param>
        /// <param name="pwd">密码</param>
        public SFTPHelper(string ip, string port, string user, string pwd)
        {
            sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
            sftp.BufferSize = uint.MaxValue;
         
            //Connect();
        }

        ~SFTPHelper()
        {
            Disconnect();
        }
        #endregion

        #region 连接SFTP
        /// <summary>
        /// 连接SFTP
        /// </summary>
        /// <returns>true成功</returns>
        public bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    sftp.Connect();
                }   
                return true;
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"连接SFTP失败,原因:{ex}");
                throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
                return false;
            }
        }
        #endregion

        #region 断开SFTP
        /// <summary>
        /// 断开SFTP
        /// </summary> 
        public void Disconnect()
        {
            try
            {
                if (sftp != null && Connected)
                {
                    sftp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"断开SFTP失败,原因:{ex}");
                throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region SFTP上传文件

        public bool IsExist(string path)
        {
            bool result = false;
            try
            {

                if (!Connected)
                    Connect();
                result = sftp.Exists(path);
                Disconnect();
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件上传失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
            }
            return result;
        }


        public void CreateDirectory(string remotePath)
        {
            try
            {
                if (!Connected)
                    Connect();
                sftp.CreateDirectory(remotePath);
                Disconnect();
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件上传失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
            }
        }

        /// <summary>
        /// SFTP上传文件
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="remotePath">远程路径</param>
        public bool Put(string localPath, string remotePath)
        {
            try
            {
                using (var file = File.OpenRead(localPath))
                {
                    if (!Connected)
                        Connect();
                    if (!Connected)
                        return false;
                    //sftp.BufferSize = uint.MaxValue;
                    //sftp.ChangeDirectory(remotePath);
                    sftp.UploadFile(file, remotePath, true);
                    Disconnect();
                }
                return true;
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件上传失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
                return false;
            }
        }
        #endregion

        #region SFTP获取文件
        /// <summary>
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public void Get(string remotePath, string localPath)
        {
            try
            {
                if (!Connected)
                    Connect();
                var byt = sftp.ReadAllBytes(remotePath);
                Disconnect();
                File.WriteAllBytes(localPath, byt);
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件获取失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
            }

        }
        #endregion

        #region 删除SFTP文件
        /// <summary>
        /// 删除SFTP文件 
        /// </summary>
        /// <param name="remoteFile">远程路径</param>
        public void Delete(string remoteFile)
        {
            try
            {
                if (!Connected)
                    Connect();
                sftp.Delete(remoteFile);
                Disconnect();
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件删除失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
            }
        }
        #endregion

        #region 获取SFTP文件列表
        /// <summary>
        /// 获取SFTP文件列表
        /// </summary>
        /// <param name="remotePath">远程目录</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <returns></returns>
        public ArrayList GetFileList(string remotePath, string fileSuffix)
        {
            var objList = new ArrayList();
            try
            {
                if (!Connected)
                    Connect();
                var files = sftp.ListDirectory(remotePath);
                Disconnect();

                foreach (var file in files)
                {
                    string name = file.Name;
                    objList.Add(name);
                }
                return objList;
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件列表获取失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message));
                return objList;
            }
        }
        #endregion

        #region 移动SFTP文件
        /// <summary>
        /// 移动SFTP文件
        /// </summary>
        /// <param name="oldRemotePath">旧远程路径</param>
        /// <param name="newRemotePath">新远程路径</param>
        public void Move(string oldRemotePath, string newRemotePath)
        {
            try
            {
                if (!Connected)
                    Connect();
                sftp.RenameFile(oldRemotePath, newRemotePath);
                Disconnect();
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件移动失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
            }
        }
        #endregion


        #region 下载
        public int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
        {
            string localFileName = localPath + "/" + fileName;
            string remoteFileName = filePath + "/" + fileName;

            try
            {
                using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
                {
                    if (!sftp.IsConnected)
                        sftp.Connect();

                    using (var file = File.OpenWrite(localFileName))
                    {
                        sftp.DownloadFile(remoteFileName, file);
                    }

                    sftp.Disconnect();
                    //Log.getInstace().WriteSysInfo("下载文件{localFileName}成功", "info");  
                    //LogManager.GetLogger("Debug").Info($"下载文件成功,文件路径:{localFileName}");
                    Console.WriteLine($"下载文件成功,文件路径:{localFileName}");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                //LogManager.GetLogger("Debug").Info($"SFTP文件移动失败,原因:{ex}");
                throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
                return -2;
            }
        }


        #endregion
    }

}

二、Tamir.Ssh

首先引用

创建类

 public class SFTPHelperTamirSharpSsh
 {
     #region 本类调用方法示例
     //SFTPHelper sftp = new SFTPHelper("127.0.11.11", "root", "root");  //端口号默认22,不需要填写
     // sftp.Connect();
     //sftp.Get("\\dpss\\b9bae449-d1cb-491d-b58e-1d149fdb78b5.gif", "D:\\");   //下载(注意斜杠)
     //sftp.Put("D:\\aa.txt", "\\dpss\\");   //上传(注意斜杠)
     //sftp.Disconnect();
     #endregion

     private Session m_session;
     private Channel m_channel;
     private ChannelSftp m_sftp;

     //host:sftp地址   user:用户名   pwd:密码        
     public SFTPHelperTamirSharpSsh(string host, string user, string pwd)
     {
         string[] arr = host.Split(':');
         string ip = arr[0];
         int port = 22;
         if (arr.Length > 1) port = Int32.Parse(arr[1]);

         JSch jsch = new JSch();
         m_session = jsch.getSession(user, ip, port);
         MyUserInfo ui = new MyUserInfo();
         ui.setPassword(pwd);
         m_session.setUserInfo(ui);

     }

     //SFTP连接状态        
     public bool Connected { get { return m_session.isConnected(); } }

     //连接SFTP        
     public bool Connect()
     {
         try
         {
             if (!Connected)
             {
                 m_session.connect();
                 m_channel = m_session.openChannel("sftp");
                 m_channel.connect();
                 m_sftp = (ChannelSftp)m_channel;
             }
             return true;
         }
         catch
         {
             return false;
         }
     }

     //断开SFTP        
     public void Disconnect()
     {
         if (Connected)
         {
             m_channel.disconnect();
             m_session.disconnect();
         }
     }

     //SFTP存放文件        
     public bool Put(string localPath, string remotePath)
     {
         try
         {
             Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
             Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(remotePath);
             m_sftp.put(src, dst);
             return true;
         }
         catch
         {
             return false;
         }
     }

     //SFTP获取文件        
     public bool Get(string remotePath, string localPath)
     {
         try
         {
             Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath);
             Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
             m_sftp.get(src, dst);
             return true;
         }
         catch
         {
             return false;
         }
     }
     //删除SFTP文件
     public bool Delete(string remoteFile)
     {
         try
         {
             m_sftp.rm(remoteFile);
             return true;
         }
         catch
         {
             return false;
         }
     }

     //获取SFTP文件列表        
     public ArrayList GetFileList(string remotePath, string fileType)
     {
         try
         {
             Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(remotePath);
             ArrayList objList = new ArrayList();
             foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
             {
                 string sss = qqq.getFilename();
                 if (sss.Length > (fileType.Length + 1) && fileType == sss.Substring(sss.Length - fileType.Length))
                 { objList.Add(sss); }
                 else { continue; }
             }

             return objList;
         }
         catch
         {
             return null;
         }
     }


     //登录验证信息        
     public class MyUserInfo : UserInfo
     {
         String passwd;
         public String getPassword() { return passwd; }
         public void setPassword(String passwd) { this.passwd = passwd; }

         public String getPassphrase() { return null; }
         public bool promptPassphrase(String message) { return true; }

         public bool promptPassword(String message) { return true; }
         public bool promptYesNo(String message) { return true; }
         public void showMessage(String message) { }

     }
 }

三、WinSCP

添加引用

下载软件放到程序根目录

创建类

 public class WinSCPHelper
 {
     /// <summary>

     /// WinSCP数据传输

     /// </summary>

     /// <param name="winscptype">选择操作方式:上传、下载</param>

     /// <param name="srcPath">源目录</param>

     /// <param name="objPath">目标目录</param>

     /// <param name="hostName">IP地址</param>

     /// <param name="userName">账户</param>

     /// <param name="password">密码</param>

     /// <returns></returns>

     public bool WinSCP(WinSCPType winscptype, string srcPath, string objPath, string hostName, string userName, string password, int portNumber, string sshHostKeyFingerprint)

     {

         try
         {
             // Setup session options
             SessionOptions sessionOptions = new SessionOptions
             {
                 Protocol = Protocol.Sftp,
                 HostName = hostName,
                 UserName = userName,
                 Password = password,
                 SshHostKeyFingerprint = sshHostKeyFingerprint   //"ssh-rsa 2048 xxxxxxxxxxx..."使用WinSCP.exe 程序,添加一个连接方式并登录。
                                                                 //登录后在Session选项中 选择 Generate Session URL/Code .查询软件生成的代码即可获取密钥
             };

             using (Session session = new Session())
             {
                 // Connect
                 session.Open(sessionOptions);

                 // Upload files
                 TransferOptions transferOptions = new TransferOptions();
                 transferOptions.TransferMode = TransferMode.Binary;

                 TransferOperationResult transferResult;
                 //transferResult =
                 //    session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);
                 switch (winscptype)

                 {

                     case WinSCPType.Download:

                         transferResult = session.GetFiles(srcPath, objPath, false, transferOptions);

                         break;

                     case WinSCPType.Upload:

                         transferResult = session.PutFiles(srcPath, objPath, false, transferOptions);

                         break;

                     default:

                         transferResult = session.GetFiles(srcPath, objPath, false, transferOptions);

                         break;

                 }

                 // Throw on any error
                 transferResult.Check();

                 // Print results
                 foreach (TransferEventArgs transfer in transferResult.Transfers)
                 {
                     //Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                     LogManager.GetLogger("Debug").Info($"Upload of {transfer.FileName} succeeded" );
                 }
             }

             return true;
         }
         catch (Exception e)
         {
             //Console.WriteLine("Error: {0}", e);
             LogManager.GetLogger("Debug").Info($"\"Error: {e}");
             return false;
         }
     }

     public enum WinSCPType

     {

         Download = 0,

         Upload = 1

     }
 }

PS:服务器搭建测试可使用freeSSHd

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
链接到sFTP客户端谷歌浏览器应用程序 访问您的本地/远程FTP服务器(包括您的NAS驱动器),本地服务器,VPS,专用服务器,云服务器或共享主机。 我们现在已经发布了适用于MAC,WINDOWS和LINUX的本地应用程序,请访问我们的网站: http://www.sftpclient.io/download ------------------------------------------ sFTP客户端是简单的,它是建立在谷歌浏览器/ Chrome操作系统打包的应用程序界面,使应用程序快速和响应。其中一些功能包括一个FTP / SFTP帐户管理器,用于存储和管理最常用和最喜欢的FTP / SFTP连接,只需点击一下,文件/文件夹队列即可查看当前正在上传/下载的项目,强大的文本编辑器(所以你甚至不需要额外的程序来修改你的代码),等等... 看看下面的sFTP客户端应用程序的所有功能。 特征: ========= - 标准的FTP连接 - SSH over File Transfer Protocol(sFTP)连接 - 用于SSH连接的权限密钥文件(SSH密钥 - RSA) - FTP / SFTP被动模式 - 连接到远程(外部)和本地(内部)FTP / SFTP / SSH服务器。 - 更改文件/文件夹权限(通过复选框或值:例如777) - 上传/下载多个文件和文件夹 - 快速连接 - 编辑器选项:选项卡式文件,自定义 - 拖放文件/文件夹 - 管理FTP / SFTP / SSH账户(使用谷歌浏览器本地存储和安全密码加密存储) - 强大的文本编辑器,语法高亮(保存,自动保存和自动上传功能) - 键盘选择(向上,向下,进入(回车)和退出(退格)的目录,包括搜索能力,通过键盘上键入快速访问文件/文件夹) - 导入帐户:sFTP客户端 - 出口帐户 - 重命名和删除文件 - 创建新的文件/目录 - 刷新本地和远程列表 - 对列进行排序和调整大小 - 多选文件和文件夹 - 按路径浏览本地和远程文件夹 - 本地目录:选择每个连接的默认本地目录,假设为全局 - 快速帐户菜单(一键从您保存的列表中打开FTP / SFTP / SSH帐户连接) - 多个FTP / SFTP / SSH帐户连接(如果您打开了大量连接,则滚动选项卡) - 关闭连接(断开与服务器的连接并删除所有活动) - 控制台日志(显示所有FTP / SFTP / SSH活动日志) - 传输队列(排队的文件和文件夹,失败的文件和文件夹,完成的文件和文件夹) - 新的Google Sockets API - 远程和本地菜单 - 连接并列出UNIX和MS-DOS目录 - 复制网址到剪贴板 - 10最近的连接 - 保持连接 - 主密码登录(保持所有的FTP连接安全,1登录) - 同步浏览 更多的功能和功能来免费未来的更新! 支持语言:English (UK)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值