• JSch包实现SFTP上传、下载


    JSch包maven仓库地址:

    <!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.54</version>
    </dependency>

     sftp 上传下载工具类

    package wenjun.zhang.jsch;
    
    import net.sf.json.JSONObject;
    
    import org.apache.commons.lang.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.SftpException;
    
    /** 
     * sftp 上传下载工具类
     */
    public class SftpUtil {
    
        private static Logger logger = LoggerFactory.getLogger(SftpUtil.class);
        
        /**
         * 获取Sftp对象
         * @param param
         * @return
         */
        public  static SftpConfig getSftpObj(String param) {
            SftpConfig sftpConfig = new SftpConfig();
            if (StringUtils.isNotBlank(param)) {
                JSONObject jsonObj = JSONObject.fromObject(param);
                sftpConfig = (SftpConfig) JSONObject.toBean(jsonObj, SftpConfig.class);
            }
            return sftpConfig;
        }
    
        /** sftp 上传*/
        public static boolean upload(SftpConfig config, String baseDir, String fileName, String filePath) {
            logger.info("路径:baseDir="+baseDir);
            SftpChannel sftpChannel = new SftpChannel();
            ChannelSftp sftp = null;
            try {
                if (StringUtils.isNotBlank(config.getPrivateKeyPath())) {
                    sftp = sftpChannel.connectByIdentity(config);
                } else {
                    sftp = sftpChannel.connectByPwd(config);
                }
                if (sftp.isConnected()) {
                    logger.info("连接服务器成功");
                } else {
                    logger.error("连接服务器失败");
                    return false;
                }
                //检查路径
                if(!isExist(sftp, baseDir)){
                    logger.error("创建sftp服务器路径失败:" + baseDir);
                    return false;
                }
                String dst = baseDir + "/" + fileName;
                String src = filePath + "/" + fileName;
                logger.info("开始上传,本地服务器路径:["+src +"]目标服务器路径:["+dst+"]");
                sftp.put(src, dst);
                logger.info("上传成功");
                return true;
            } catch (Exception e) {
                logger.error("上传失败", e);
                return false;
            } finally {
                sftpChannel.closeChannel();
            }
        }
    
        /**sftp 下载 */
        public static boolean down(SftpConfig config, String baseDir, String fileName1, String filePath, String fileName2 ) {
            SftpChannel sftpChannel = new SftpChannel();
            ChannelSftp sftp = null;
            try {
                if (StringUtils.isNotBlank(config.getPrivateKeyPath())) {
                    sftp = sftpChannel.connectByIdentity(config);
                } else {
                    sftp = sftpChannel.connectByPwd(config);
                }
                if (sftp.isConnected()) {
                    logger.info("连接服务器成功");
                } else {
                    logger.error("连接服务器失败");
                    return false;
                }
                String dst = "";
                if (StringUtils.isBlank(fileName2)) {
                    dst = filePath + fileName1;
                } else{
                    dst = filePath + fileName2;
                }
                String src = baseDir+ "/" + fileName1;
                logger.info("开始下载,sftp服务器路径:["+src +"]目标服务器路径:["+dst+"]");
                sftp.get(src, dst);
                logger.info("下载成功");
                return true;
            } catch (Exception e) {
                logger.error("下载失败", e);
                return false;
            } finally {
                sftpChannel.closeChannel();
            }
        }
        
        /**
         * 判断文件夹是否存在
         * true 目录创建成功,false 目录创建失败
          * @param sftp
         * @param filePath 文件夹路径
         * @return
         */
        public static boolean isExist(ChannelSftp sftp, String filePath) {
            String paths[] = filePath.split("\/");
            String dir = paths[0];
            for (int i = 0; i < paths.length - 1; i++) {
                dir = dir + "/" + paths[i + 1];
                try{
                    sftp.cd(dir);
                }catch(SftpException sException){
                    if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){
                        try {
                            sftp.mkdir(dir);
                        } catch (SftpException e) {
                            e.printStackTrace();
                            return false;
                        }
                    }
                }
            }
            return true;
        }
    }

    SftpChannel  sftp连接

    package wenjun.zhang.jsch;
    
    import java.util.Properties;
    
    import org.apache.commons.lang.StringUtils;
    
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    
    public class SftpChannel {
        Session session = null;
        Channel channel = null;
    
        //端口默认为22
        public static final int SFTP_DEFAULT_PORT = 22;
    
        /** 利用JSch包实现SFTP下载、上传文件(秘钥方式登陆)*/
        public ChannelSftp connectByIdentity(SftpConfig sftpConfig) throws JSchException {
            JSch jsch = new JSch();
            int port = SFTP_DEFAULT_PORT;
            //设置密钥和密码
            //支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了
            if (StringUtils.isNotBlank(sftpConfig.getPrivateKeyPath())) {
                if (StringUtils.isNotBlank(sftpConfig.getPassphrase())) {
                    //设置带口令的密钥
                    jsch.addIdentity(sftpConfig.getPrivateKeyPath(), sftpConfig.getPassphrase());
                } else {
                    //设置不带口令的密钥
                    jsch.addIdentity(sftpConfig.getPrivateKeyPath());
                }
            }
            if (sftpConfig.getPort() != null) {
                port = Integer.valueOf(sftpConfig.getPort());
            }
            if (port > 0) {
                //采用指定的端口连接服务器
                session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp(), port);
            } else {
                //连接服务器,采用默认端口
                session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp());
            }
            if (session == null) {
                throw new JSchException("session为空,连接失败");
            }
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            session.setTimeout(30000);
            session.connect();
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect();
            return (ChannelSftp) channel;
        }
    
        /** 利用JSch包实现SFTP下载、上传文件(用户名密码方式登陆) */
        public ChannelSftp connectByPwd(SftpConfig sftpConfig) throws JSchException {
            JSch jsch = new JSch();
            int port = SFTP_DEFAULT_PORT;
            if (sftpConfig.getPort() != null) {
                port = Integer.valueOf(sftpConfig.getPort());
            }
            if (port > 0) {
                //采用指定的端口连接服务器
                session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp(), port);
            } else {
                //连接服务器,采用默认端口
                session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getIp());
            }
            if (session == null) {
                throw new JSchException("session为空,连接失败");
            }
            //设置登陆主机的密码
            session.setPassword(sftpConfig.getPwd());//设置密码
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            session.setTimeout(30000);
            session.connect();
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect();
            return (ChannelSftp) channel;
        }
    
        public void closeChannel() {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    
    }

    sftp配置类

    package wenjun.zhang.jsch;
    
    /**
     * sftp 配置
     */
    public class SftpConfig {
        /** 密钥地址 */
        private String privateKeyPath;
        /** 口令 */
        private String passphrase;
        
        private String ip;
        
        private Integer port;
        
        private String username;
        
        private String pwd;
        
        private String path;
        
        private String baseDir;
        
        public String getIp() {
            return ip;
        }
    
        public void setIp(String ip) {
            this.ip = ip;
        }
    
        public Integer getPort() {
            return port;
        }
    
        public void setPort(Integer port) {
            this.port = port;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        public String getPath() {
            return path;
        }
    
        public void setPath(String path) {
            this.path = path;
        }
    
        public String getBaseDir() {
            return baseDir;
        }
    
        public void setBaseDir(String baseDir) {
            this.baseDir = baseDir;
        }
    
        public String getPrivateKeyPath() {
            return privateKeyPath;
        }
    
        public void setPrivateKeyPath(String privateKeyPath) {
            this.privateKeyPath = privateKeyPath;
        }
    
        public String getPassphrase() {
            return passphrase;
        }
    
        public void setPassphrase(String passphrase) {
            this.passphrase = passphrase;
        }
    
    }
    『愿你我既可以朝九晚五,又能够浪迹天涯』
  • 相关阅读:
    Install the Maven in your computer
    《李嘉诚全传》--孙良珠
    Crystal Reports 2008(水晶报表) 第一个报表
    《唤醒心中的巨人》--[美]安东尼·罗宾
    《写给女人》--[美]桃乐丝·卡耐基
    Crystal Reports 2008(水晶报表) JDBC连接mysql数据库
    Crystal Reports 2008(水晶报表) 启动时检查更新
    Crystal Reports 2008(水晶报表) 安装
    《百年孤独》--[哥伦比亚]加夫列尔·加西亚·马尔克斯
    《自己拯救自己》--[英]塞缪尔·斯迈尔斯
  • 原文地址:https://www.cnblogs.com/zjwwljty/p/8548468.html
Copyright © 2020-2023  润新知