Instructions for using JSch to connect Sftp

Preface

Recently, I need to pass SSH Then on SFTP Connect, and then operate, so record here, convenient for future use, also convenient for everyone as a reference.

text

First of all, you need to make a dependency reference to JSch, and the project is built by gradle.
Here is the build.gradle Code:

// https://mvnrepository.com/artifact/com.jcraft/jsch
compile group: 'com.jcraft', name: 'jsch', version: '0.1.54'

Then we need an entity class to configure the relevant parameters of our JSch.
Tips: the company uses AWS, and the parameters are all configured in ECS. So I need to take the corresponding value from the environment variable. You can change it to hard code.
Entity class:

public class SftpConfigProperties {

    public static final String environment=System.getenv("PUBLISHER_ENVIRONMENT");

    public static final String sftpUsername=System.getenv("PUBLISHER_SFTP_USERNAME");

    public static final String sftpHost=System.getenv("PUBLISHER_SFTP_HOST");

    public static final int sftpPort=Integer.valueOf(System.getenv("PUBLISHER_SFTP_PORT"));

    public static final String sftpPassword=System.getenv("PUBLISHER_SFTP_PASSWORD");

    public static final String sftpFilePath="/"+environment+"/dir_publisher_sftp";
}

Finally, the most important is the main class of jsch:
The code is as follows:

package com.harry.jsch;

import com.jcraft.jsch.*;
import com.kingland.dst.config.SftpConfigProperties;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

/**
 * this method is used to connect to sftp with jsch
 */
public class SftpConnectUtil {
    private  static Logger logger=Logger.getLogger(SftpConnectUtil.class);

    /**
     * This method is used to connect to sftp
     * @param ip
     * @param user
     * @param password
     * @param port
     * @return session
     */
    public  Session connect(String ip,String user,String password,int port){
        logger.info("start to connect to sftp");
        Session session=null;
        JSch jsch=new JSch();
        try {
            //Give the user name, ip address and port number required for connection
            session=jsch.getSession(user, ip, port);
            //When you log in for the first time, do you need a prompt? value can be filled in yes, no or ask
            session.setConfig("StrictHostKeyChecking", "no");
           //Set whether to time out
             session.setTimeout(10000);
           //Set password
            session.setPassword(password);
            //Create connection
            session.connect();
            logger.info("sftp session set properties success");
        } catch (JSchException e) {
            e.printStackTrace();
        }
        if(session == null) {
            logger.error("session is null");
        }else if(session.isConnected() == true) {
            logger.info("connet to sftp server is successful");
        }
        return session;
    }

    /**
     * This method is used to upload files
     * @param session
     * @param filePath
     * @param fileName
     */
    public  void uploadFile(Session session,String filePath,String fileName) {
        ChannelSftp channel =null;
        String filePathName=filePath+File.separator+fileName;
        FileInputStream fis =null;
        try {
            fis = new FileInputStream(new File(filePathName));
            // To create a connection, sftp
            channel =(ChannelSftp)session.openChannel("sftp");
            channel.connect();
            channel.cd(SftpConfigProperties.sftpFilePath);
            channel.put(fis, fileName);
            channel.exit();
            fis.close();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //This method is used to delete the corresponding files on sftp
    //The ls method is used to extract all the file names under the specified folder
    //After traversal, get the file name for deletion. Before deletion, give judgment conditions or make the file name
    public void deleteExpireFile(ChannelSftp channel){
        Vector vector=channel.ls(SftpConfigProperties.sftpFilePath);
        for(Object obj:vector){
            if(obj instanceof ChannelSftp.LsEntry){
                String fileName=((ChannelSftp.LsEntry) obj).getFilename();
                if (".".equals(fileName) || "..".equals(fileName)) {
                    continue;
                }
                channel.rm(fileName);
                logger.info("success delete the file :"+SftpConfigProperties.sftpFilePath+File.separator+fileName);
            }
        }
    }
}

Last

Thank you for watching. I hope it can help you

Tags: Java Session sftp Gradle

Posted on Fri, 13 Dec 2019 12:41:36 -0500 by jrmckee