SFTP文件下載

FTP並非惟一的上傳文件的方法,大部分狀況下均可使用sftp代替。sftp是什麼呢?java

sftp是Secure File Transfer Protocol的縮寫,安全文件傳送協議。能夠爲傳輸文件提供一種安全的加密方法。sftp 與 ftp 有着幾乎同樣的語法和功能。SFTP 爲 SSH的一部分,SFTP是使用加密傳輸認證信息和傳輸的數據,因此,使用SFTP是很是安全的。可是,因爲這種傳輸方式使用了加密/解密技術,因此傳輸效率比普通的FTP要低一些。

sftp是不須要另外安裝的,由於是SSH自帶的,因此會更省系統資源,也不須要單獨配置,對新手來講比較簡單。安全

Windows下面常見的FTP客戶端Filezilla、Flashfxp、Winscp、cuteftp等都是支持sftp的,只須要在登錄時選擇sftp協議,輸入SSH的帳號密碼。服務器

下面是使用.NET程序登錄SFTP下載文件的方法session

SFTPHELPER文件提供方法:ui

 
 

using Tamir.SharpSsh;
using Tamir.SharpSsh.jsch;this

//----------------須要包含的命名空間加密


public
class SFTPHelper { private Session m_session; private Channel m_channel; private ChannelSftp m_sftp; log4net.ILog log = log4net.LogManager.GetLogger("SFTPDownload"); //host:sftp地址 user:用戶名 pwd:密碼 public SFTPHelper(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); //log.Info("m_session:"+m_session.ToString()+" - "+m_session.isConnected()); 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) { //log.Info("start connect 1"); //m_session.setClientVersion("SSH-2.0-SharpSSH-1.1.1.13-JSCH-0.1.28"); m_session.connect(); //log.Info("start connnect 2"); m_channel = m_session.openChannel("sftp"); m_channel.connect(); //log.Info("channel connect"); m_sftp = (ChannelSftp)m_channel; //log.Info(m_session.getServerVersion()+" - "+m_session.getClientVersion()); } return true; } catch(Exception exp) { log.Info("登錄失敗緣由:"+exp.ToString()); 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(Exception exp) { log.Info("文件下載失敗緣由:" + exp.ToString()); return false; } } //刪除SFTP文件 public bool Delete(string remoteFile) { try { m_sftp.rm(remoteFile); return true; } catch (Exception exp) { log.Info("文件刪除失敗緣由:" + exp.ToString()); 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) && sss != "." && sss!= "..") { objList.Add(sss); } else { continue; } } return objList; } catch (Exception exp) { log.Info("文件列表獲取失敗緣由:" + exp.ToString()); 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) { } } }

調用上面的文件:spa

public void DownFtpFiles()
        {
            //log4net.Config.XmlConfigurator.Configure();
            
            while (true)
            {                   
                SFTPHelper sftphelper = new SFTPHelper(ftpIP, ftpUserName, ftpPassword);
                try{                    
                    System.Threading.Thread.Sleep(10000);
                    log.Info("開始登錄FTP服務器");                    
                    //LogHelper.WriteLog("開始登錄FTP服務器");
                    bool bconn = sftphelper.Connect();
                    if (bconn)
                    {
                        log.Info("登錄成功");
                        ArrayList objList = new ArrayList();
                        objList = sftphelper.GetFileList(ftpRoot, "dat");
                        log.Info("文件列表獲取成功");

                        string fileName = null;
                        foreach (object obj in objList)
                        {
                            string fileUrl = obj.ToString();
                            fileName = fileUrl;
                            try
                            {                               
                                
                                    log.Info("開始下載," + fileUrl);
                                    sftphelper.Get(ftpRoot + "/" + fileUrl, tempFileDir + "\\" + fileName);
                                    File.Move(tempFileDir + "\\" + fileName, downloadFileDir + "\\" + fileName);

                                    //記錄到已下載的列表中
                                    //this.AppendDownloaded(fileUrl);
                                    //刪除遠程文件
                                    sftphelper.Delete(ftpRoot + "/" + fileUrl);

                                    log.Info("下載成功," + ftpRoot + "/" + fileUrl);
                                
                            }
                            catch (Exception exp)
                            {
                                log.Info("下載或移動失敗," + fileUrl + ",緣由是:" + exp.ToString());
                            }
                        }

                    }
                    else
                    {
                        log.Info("登錄失敗");
                    }
                }                 
                catch (Exception exp)
                {
                    log.Info("下載或移動失敗,緣由是:" + exp.ToString());
                }
                finally
                {
                    try
                    {
                        sftphelper.Disconnect();                        
                    }
                    catch (Exception ex)
                    {
                        log.Info("關閉FTP鏈接異常,緣由是:" + ex.ToString());
                    }
                }
            }
        }

 

SFTP所需的組件code

相關文章
相關標籤/搜索