C# 对接sftp(项目中用到)

在项目中用到的是获取文件列表和下载文件,这个是可以的,其他应该也没问题

在对接sftp时必须引用的三个dll文件,可以从newGet包管理里面下载

DiffieHellman

Org.Mentalis.Security

Tamir.SharpSSH

我们是做了一个exe用sqlserver的job进行调用的

  //sftp信息
        static string strFileName = ConfigurationSettings.AppSettings["FileUrl"];
        static string SftpFilepath = ConfigurationSettings.AppSettings["SftpFilepath"];
        static string ftpid = ConfigurationSettings.AppSettings["SftpServerIp"];
        static string userName = ConfigurationSettings.AppSettings["SftpUserName"];
        static string UserPwd = ConfigurationSettings.AppSettings["SftpUserPwd"];
        static string conString = ConfigurationSettings.AppSettings["conString"];
        static string DMTconString = ConfigurationSettings.AppSettings["DMTconString"];

        //邮件用到
        static SmtpContext context = new SmtpContext();
        static string FromMial = ConfigHelper.GetConfigStr("FromMial");//发送方
        static string ToMial = ConfigHelper.GetConfigStr("ToMial");//接收者
        static string CCMial = ConfigHelper.GetConfigStr("CCMial");//抄送者
        static string dir = AppDomain.CurrentDomain.BaseDirectory;
        static string SFTPfile = ConfigHelper.GetConfigStr("SFTPfile");

        static void Main(string[] args)
        {
            context.Server = ConfigHelper.GetConfigStr("EmailServerAddress");//smtp地址
            context.Port = ConfigHelper.GetConfigStr("EmailServerPort").CastToInt32();//端口号
            context.UserName = ConfigHelper.GetConfigStr("UserName");//UserAccount
            context.Password = ConfigHelper.GetConfigStr("Password");//PWD
            SftpBll sftpBll = new SftpBll();
            try
            {
                //文件列表
                ArrayList FileList = sftpBll.FileList(conString, SftpFilepath);
                if (FileList.Count > 0)
                {
                    //从sftp上下载文件
                    sftpBll.SFtpDownload(FileList, SftpFilepath, ftpid, userName, UserPwd);
                    //将获取到的文件写入数据库
                    int n = sftpBll.AddFileRecord(conString, FileList, strFileName);
                }

            }
            catch (Exception ex)
            {
                
            }
        }

关于sftp的的bll做一些处理,调用helper

 public class SftpBll
    {
        static string ftpid = ConfigHelper.GetConfigStr("SftpServerIp");
        static string userName = ConfigHelper.GetConfigStr("SftpUserName");
        static string UserPwd = ConfigHelper.GetConfigStr("SftpUserPwd");
        static string FileUrl = ConfigHelper.GetConfigStr("FileUrl");
        static string FileName = ConfigHelper.GetConfigStr("FileName");
        clsSFTPHelper objSFtp = new clsSFTPHelper(ftpid, userName, UserPwd, 22);
        /// <summary>
        /// 从sftp上下载文件
        /// </summary>
        /// <param name="strFileName"></param>
        /// <param name="SftpFilepath"></param>
        /// <param name="ftpid"></param>
        /// <param name="userName"></param>
        /// <param name="UserPwd"></param>
        /// <returns></returns>
        public void SFtpDownload(ArrayList FileList, string SftpFilepath, string ftpid, string userName, string UserPwd)
        {
            //SFtp IP:服务器的IP,UserName:登录名,PAW:密码
            objSFtp.Connect();
            if (objSFtp.Connected)
            {
                //获取文件列表
                foreach (var item in FileList)
                {
                    Log.CreateLogManager().Debug(SftpFilepath + "/" + item.ToString() + FileUrl);
                    objSFtp.Get(SftpFilepath + "/" + item.ToString(), FileUrl);
                }

            }
            objSFtp.Disconnect();

        }
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="destPath"></param>
        /// <returns></returns>
        public ArrayList MoveFile(string sourcePath, string destPath)
        {
            ArrayList existFile = new ArrayList();
            destPath += DateTime.Now.ToString("yyyyMMddhhmmss");
            if (Directory.Exists(sourcePath))
            {
                if (!Directory.Exists(destPath))
                {
                    //目标目录不存在则创建  
                    try
                    {
                        Directory.CreateDirectory(destPath);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("创建目标目录失败:" + ex.Message);
                    }
                }
                //获得源文件下所有文件  
                List<string> files = new List<string>(Directory.GetFiles(sourcePath));
                files.ForEach(c =>
                {
                    string destFile = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
                    if (File.Exists(destFile))
                    {
                        existFile.Add(destFile);
                    }
                    else
                    {
                        File.Move(c, destFile);
                    }
                });
            }
            return existFile;
        }

        }
    }

关于sftp的helper

public class clsSFTPHelper
 {
     private Session m_session;
     private Channel m_channel;
     private ChannelSftp m_sftp;
 
     //host:sftp地址   user:用户名   pwd:密码       
     public clsSFTPHelper(string server, string user, string pwd, int port)
     {
         JSch jsch = new JSch();
         m_session = jsch.getSession(user, server, 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 (Exception ex)
         {
             throw ex;
         }
     }
 
     //断开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 (Exception ex)
         {
             throw ex;
         }
     }
 
     //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 (Exception ex)
         {
            Log.CreateLogManager().Debug(ex.Message);
            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) { Console.WriteLine(message); }
 
     }
 }

 

posted @ 2021-04-20 16:43  看花人墨客  阅读(2405)  评论(0编辑  收藏  举报