자바 jsch 를 이용 하여 sftp 도구 류 조작

8751 단어
package cn.fraudmetrix.luna.biz.util;

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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * sftp     Created by jie on 2018/7/18.
 */
public class SFTPHelper implements Closeable {

    private final static Logger log         = LoggerFactory.getLogger(SFTPHelper.class);

    private Session session;
    private ChannelSftp channelSftp;

    /**
     *    ,   
     */
    private final static int    TIMEOUT     = 60000;
    private final static int    BYTE_LENGTH = 1024;

    public SFTPHelper(String userName, String password, String host){
        try {
            String[] arr = host.split(":");
            String ip = arr[0];
            int port = arr.length > 1 ? Integer.parseInt(arr[1]) : 22;

            JSch jSch = new JSch();
            session = jSch.getSession(userName, ip, port);
            if (null != password) {
                session.setPassword(password);
            }
            session.setTimeout(TIMEOUT);
            Properties properties = new Properties();
            properties.put("StrictHostKeyChecking", "no");
            session.setConfig(properties);
        } catch (Exception e) {
            log.error("init host:{},userName:{},password:{} error:{}",host,userName,password, e);
        }
    }

    /**
     *           :        close      
     * 
     * @see SFTPHelper#close()
     * @return
     */
    public boolean connection() {
        try {
            if (!isConnected()) {
                session.connect();

                channelSftp = (ChannelSftp) session.openChannel("sftp");
                channelSftp.connect();

                log.info("connected to host:{},userName:{}", session.getHost(), session.getUserName());
            }
            return true;
        } catch (JSchException e) {
            log.error("connection to sftp host:{} error:{}", session.getHost(), e);
            return false;
        }
    }

    /**
     *  sftp                
     * 
     * @param remoteFile        +fileName
     * @param localPath         
     * @return
     */
    public boolean get(String remoteFile, String localPath) {
        if (isConnected()) {
            try {
                channelSftp.get(remoteFile, localPath);
                return true;
            } catch (SftpException e) {
                log.error("get remoteFile:{},localPath:{}, error:{}", remoteFile, localPath, e);
            }
        }
        return false;
    }

    /**
     *   sftp       
     * 
     * @param remoteFile
     * @return
     */
    public byte[] getFileByte(String remoteFile) {
        byte[] fileData;
        try (InputStream inputStream = channelSftp.get(remoteFile)) {
            byte[] ss = new byte[BYTE_LENGTH];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int rc = 0;
            while ((rc = inputStream.read(ss, 0, BYTE_LENGTH)) > 0) {
                byteArrayOutputStream.write(ss, 0, rc);
            }
            fileData = byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            log.error("getFileData remoteFile:{},error:{}", remoteFile, e);
            fileData = null;
        }
        return fileData;
    }

    /**
     *   sftp   (  )    ,         
     *
     * @param remoteFile
     * @param charsetName
     * @return
     */
    public List getFileLines(String remoteFile,String charsetName) {
        List fileData;
        try (InputStream inputStream = channelSftp.get(remoteFile);
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charsetName);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            String str;
            fileData = new ArrayList<>();
            while((str = bufferedReader.readLine()) != null){
                fileData.add(str);
            }
        } catch (Exception e) {
            log.error("getFileData remoteFile:{},error:{}", remoteFile, e);
            fileData = null;
        }
        return fileData;
    }

    /**
     *        sftp       
     * 
     * @param localFile
     * @param remoteFile
     * @return
     */
    public boolean put(String localFile, String remoteFile) {
        if (isConnected()) {
            try {
                channelSftp.put(localFile, remoteFile);
                return true;
            } catch (SftpException e) {
                log.error("put localPath:{}, remoteFile:{},error:{}", localFile, remoteFile, e);
                return false;
            }
        }
        return false;
    }

    /**
     *  sftp         
     * 
     * @param remoteFile
     * @return
     */
    public boolean delFile(String remoteFile) {
        if (isConnected()) {
            try {
                channelSftp.rm(remoteFile);
                return true;
            } catch (SftpException e) {
                log.error("delFile remoteFile:{} , error:{}", remoteFile, e);
            }
        }
        return false;
    }

    /**
     *            
     * @param remotePath
     * @return
     */
    public Vector ls(String remotePath){
        Vector vector = null;
        if(isConnected()){
            try {
                vector = channelSftp.ls(remotePath);
            } catch (SftpException e) {
                vector = null;
                log.error("ls remotePath:{} , error:{}",remotePath,e);
            }
        }
        return vector;
    }

    /**
     *            
     * @param remotePath
     * @param filenamePattern
     * @return
     *        ./ ../      ,               
     */
    public List lsFiles(String remotePath,Pattern filenamePattern){
        List lsEntryList = null;
        if(isConnected()){
            try {
                Vector vector = channelSftp.ls(remotePath);
                if(vector != null) {
                    lsEntryList = vector.stream().filter(x -> {
                        boolean match = true;
                        if(filenamePattern != null){
                            Matcher mtc = filenamePattern.matcher(x.getFilename());
                            match = mtc.find();
                        }
                        if (match && !x.getAttrs().isDir() && !x.getAttrs().isLink()) {
                            return true;
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
            } catch (SftpException e) {
                lsEntryList = null;
                log.error("lsFiles remotePath:{} , error:{}",remotePath,e);
            }
        }
        return lsEntryList;
    }

    /**
     *          
     * 
     * @return
     */
    public boolean isConnected() {
        if (session.isConnected() && channelSftp.isConnected()) {
            return true;
        }
        log.info("sftp server:{} is not connected",session.getHost());
        return false;
    }

    /**
     *       
     */
    @Override
    public void close() throws IOException {
        if (channelSftp != null && channelSftp.isConnected()) {
            channelSftp.quit();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
        log.info("session and channel is closed");
    }

    public static void main(String[] args) throws FileNotFoundException {

        try(SFTPHelper sftpHelper = new SFTPHelper("vip001", "155d1e33274", "10.58.10.179")) {
            if (sftpHelper.connection()) {
//                 boolean result = sftpHelper.get("/data/sftp/vip001/file/luna/newnew_result_20180730.txt","/tmp/luna/newnew_result_20180730.txt");
                // boolean result = sftpHelper.get("/data/sftp/vip001/file/app.log","/tmp/app.log");
                // boolean result = sftpHelper.put("/tmp/app.log","/data/sftp/vip001/file/app.log");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

좋은 웹페이지 즐겨찾기