1. 程式人生 > >JSCH通過sftp下載檔案

JSCH通過sftp下載檔案

此文轉載:

博文原地址:https://blog.csdn.net/sinat_34620530/article/details/54311732

尊重原創!

使用jsch通過ftps連線伺服器端下載檔案
Session session=jsch.getSession(ftpUserName, ftpHost, ftpPort);
session.setPassword(ftpPassword);
session.connect();
ChannelSftp channel = (ChannelSftp) s

ession.openChannel(“sftp”);
獲取到channel通過ChannelSftp 的相關方法上傳或是下載檔案
channel.get(remoteFile, output);
channel.put(input, newName);
使用完成後關閉session,關閉channel
channel.disconnect();
session.disconnect();

程式程式碼:

jsch-0.1.54.jar

Logger.jar

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

 public class SFTPProcessor {
     private static Session session = null;
     private static ChannelSftp channel = null;
     private static Logger logger = Logger.getLogger(SFTPProcessor.class);



     public static ChannelSftp getConnect() {
        String ftpHost = SysPropUtil.getValue("download.host");
          String port = SysPropUtil.getValue("download.port");
          String ftpUserName = SysPropUtil.getValue("download.username");
          String ftpPassword = SysPropUtil.getValue("download.pass");
          //預設的埠22 此處我是定義到常量類中;
          int ftpPort = 22;
          //判斷埠號是否為空,如果不為空,則賦值
          if (port != null && !port.equals("")) {
              ftpPort = Integer.valueOf(port);
          }
          JSch jsch = new JSch(); // 建立JSch物件
          // 按照使用者名稱,主機ip,埠獲取一個Session物件
          try {
              logger.info("sftp [ ftpHost = "+ftpHost+"  ftpPort = "+ftpPort+"  ftpUserName = "+ftpUserName+"  ftpPassword = "+ftpPassword+" ]");
               session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
               logger.info("Session created.");
               if (ftpPassword != null) {
                session.setPassword(ftpPassword); // 設定密碼
               }
               String ftpTO=SysPropUtil.getValue("download.timeout");
               if (!(ftpTO==null||"".equals(ftpTO))) {
                   int ftpTimeout=Integer.parseInt(ftpTO);
                   session.setTimeout(ftpTimeout); // 設定timeout時候
               }
               //並且一旦計算機的密匙發生了變化,就拒絕連線。
               session.setConfig("StrictHostKeyChecking", "no");
               //預設值是 “yes” 此處是由於我們SFTP伺服器的DNS解析有問題,則把UseDNS設定為“no”
               session.setConfig("UseDNS", "no");
               session.connect(); // 經由過程Session建樹連結
               logger.debug("Session connected.");
               logger.debug("Opening SFTP Channel.");
               channel = (ChannelSftp) session.openChannel("sftp"); // 開啟SFTP通道
               channel.connect(); // 建樹SFTP通道的連線
               logger.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = "
                 + ftpUserName + ", returning: " + channel);
          } catch (JSchException e) {
           // TODO Auto-generated catch block
              e.printStackTrace();
              logger.error("sftp getConnect error : "+e);
          }
          return channel;
     }

     public static void closeChannel() throws Exception {
          try {
               if (channel != null) {
                   channel.disconnect();
               }
               if (session != null) {
                   session.disconnect();
               }
          } catch (Exception e) {
               logger.error("close sftp error", e);
               throw new Exception( "close ftp error.");
          }
     }


     public static void uploadFile(String localFile, String newName, String remoteFoldPath) throws Exception{
          InputStream input = null;
          try {
             input = new FileInputStream(new File(localFile));
           // 改變當前路徑到指定路徑 
           channel.cd(remoteFoldPath);
           channel.put(input, newName);
          } catch (Exception e) {
           logger.error("Upload file error", e);
           throw new Exception( "Upload file error.");
          } finally {
           if (input != null) {
            try {
             input.close();
            } catch (IOException e) {
             throw new Exception("Close stream error.");
            }
           }
          }
     }


     public void downloadFile(String remoteFile, String remotePath, String localFile) throws Exception {
          logger.info("sftp download File remotePath :"+remotePath+File.separator+remoteFile+" to localPath : "+localFile+" !");
          OutputStream output = null;
          File file = null;
          try {
               file = new File(localFile);
               if (!checkFileExist(localFile)) {
                file.createNewFile();
               }
               output = new FileOutputStream(file);
               channel.cd(remotePath);
               channel.get(remoteFile, output);
          } catch (Exception e) {
               logger.error("Download file error", e);
               throw new Exception("Download file error.");
          } finally {
               if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        throw new Exception("Close stream error.");
                    }
               }

          }
     }


     @SuppressWarnings("unchecked")
     public Vector listFiles(String remotePath) throws Exception {
          Vector vector = null;
          try {
           vector = channel.ls(remotePath);
          } catch (SftpException e) {
           logger.error("List file error", e);
           throw new Exception("list file error.");
          }
          return vector;
     }


     private boolean checkFileExist(String localPath) {
          File file = new File(localPath);
          return file.exists();
     }

     public static void main(String[] args) throws Exception {
        //初始化配置檔案
        try {
            SysPropUtil.init("\\updconfig.properties");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         SFTPProcessor ftpUtil = new SFTPProcessor();
         ChannelSftp channeltest = ftpUtil.getConnect();
         System.out.println(channeltest.isConnected());
         ftpUtil.downloadFile("cussplus_3.5.0.1.zip.001", "/opt/applog/msiUpdate/Kiosk/3.7/COMMON/PEK", "E:\\projectTest\\downloadPath\\cussplus_3.5.0.1.zip.001");
         ftpUtil.closeChannel();
         System.out.println(channeltest.isConnected());
     }
 }