美文网首页
Jsch实现SFTP功能

Jsch实现SFTP功能

作者: 胖胖的半山兄 | 来源:发表于2017-10-27 15:12 被阅读0次

项目中图片的上传需要支持SFTP的功能,权衡了下,打算使用Jsch。如果有啥不好实现的功能还是可以通过操作shell实现的

  1. 下载jar包
    pom 添加
<dependency>
        <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>
  1. 创建连接
 /**
     * Description: <br>
     * 
     * @author xxx<br>
     * @taskId <br>
     * @param sftpIp <br>
     * @param userName <br>
     * @param password <br>
     * @return <br>
     */
    public static ChannelSftp connect(String sftpIp, String userName, String password) {
        // 已定义 private static final int DEFAULT_SSH_PORT = 22;
        logger.debug("sftp connect begin. host=[{}],port=[{}],username=[{}],password=[{}]", sftpIp, DEFAULT_SSH_PORT,
            userName, password);
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession(userName, sftpIp, DEFAULT_SSH_PORT);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // sshSession 记得关闭
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        }
        catch (JSchException e) {
            logger.error(e);
        }
        logger.debug("sftp connect end.");
        return sftp;
    }
  1. 查询文件列表
 /**
     * Description: <br>
     * 
     * @author xxx<br>
     * @taskId <br>
     * @param sftp <br>
     * @param fileDir <br>
     * @return <br>
     */
    @SuppressWarnings("unchecked")
    public static Vector<LsEntry> listFiles(ChannelSftp sftp, String fileDir) {
        Vector<LsEntry> files = new Vector<LsEntry>();
        try {
            files = sftp.ls(fileDir);
        }
        catch (Exception e) {
            logger.error(e);
        }
        return files;
    }
  1. 判断目录是否存在
 /**
     * Description: <br>
     * 
     * @author xxx<br>
     * @taskId <br>
     * @param sftp <br>
     * @param fileDir <br>
     * @return <br>
     */
    private static boolean checkDirExist(ChannelSftp sftp, String fileDir) {
        boolean isExist = false;
        int index = fileDir.lastIndexOf("/");
        String offerCode = fileDir.substring(index + 1);
        String PFileDir = fileDir.substring(0, index + 1);

        Vector<LsEntry> files = new Vector<LsEntry>();
        try {
            files = listFiles(sftp, PFileDir);
        }
        catch (Exception e) {
            logger.error(e);
        }
        Iterator<LsEntry> fileIterator = files.iterator();
        while (fileIterator.hasNext()) {
            LsEntry lsEntry = fileIterator.next();
            if (offerCode.equals(lsEntry.getFilename())) {
                isExist = true;
                break;
            }
        }
        return isExist;
    }
  1. 上传文件
   /**
     * Description: 上传一个文件到FTP服务器,先创建目录<br>
     * 
     * @author xxx<br>
     * @taskId <br>
     * @param ftpIp <br>
     * @param userName <br>
     * @param password <br>
     * @param fileDir <br>
     * @param fileName <br>
     * @param localFile <br>
     * @throws BaseAppException <br>
     */
    public static void uploadFile(String ftpIp, String userName, String password, String fileDir, String fileName,
        String localFile) throws BaseAppException {
        ChannelSftp sftp = null;
        try {
            sftp = connect(ftpIp, userName, password);
            // 判断目录是否存在
            if (!checkDirExist(sftp, fileDir)) {
                sftp.mkdir(fileDir);
            }
            sftp.cd(fileDir);
            File file = new File(localFile);
            sftp.put(new FileInputStream(file), file.getName());

        }
        catch (Exception e) {
            logger.error(e);
            ExceptionHandler.publish("S-DMT-UM-00018", ExceptionHandler.BUSS_ERROR);
        }
        finally {
            try {
                //没有关闭session,会导致服务器sshd进程未关闭
                sftp.getSession().disconnect();
                sftp.disconnect();
            }
            catch (Exception e) {
                logger.error(e);
            }
        }
    }
  1. 删除目录
/**
     * Description: <br>
     * 
     * @author zhao.weiwei<br>
     * @taskId <br>
     * @param sftpIp <br>
     * @param userName <br>
     * @param password <br>
     * @param fileDir <br>
     * @throws BaseAppException <br>
     */
    public static void deleteFtpDir(String sftpIp, String userName, String password, String fileDir)
        throws BaseAppException {
        ChannelSftp sftp = null;
        try {
            sftp = connect(sftpIp, userName, password);
            sftp.cd(fileDir);

            // 先删除目录下的文件
            Vector<LsEntry> files = listFiles(sftp, fileDir);
            Iterator<LsEntry> fileIterator = files.iterator();
            while (fileIterator.hasNext()) {
                LsEntry lsEntry = fileIterator.next();
                String fileName = lsEntry.getFilename();
                if (!".".equals(fileName) && !"..".equals(fileName)) {
                    sftp.rm(fileName);
                }
            }
            sftp.rmdir(fileDir);
        }
        catch (Exception e) {
            logger.error(e);
            ExceptionHandler.publish("S-DMT-UM-00019", ExceptionHandler.BUSS_ERROR);
        }
        finally {
            try {
                //没有关闭session,会导致服务器sshd进程未关闭
                sftp.getSession().disconnect();
                sftp.disconnect();
            }
            catch (Exception e) {
                logger.error(e);
            }
        }
    }

相关文章

网友评论

      本文标题:Jsch实现SFTP功能

      本文链接:https://www.haomeiwen.com/subject/ubzkpxtx.html