sringboot 使用sftp

java/sringboot 使用sftp上传、下载,多个sftp互传!

1.application.yml 配置信息

2.Sftp1Util,Sftp2Util类

---------------------直接代码

application.yml (配置两个SFTP,用下下面互传)

#============================================================================
# SFTP1 填写自己服务器信息
#============================================================================
sftp1:
  client:
    protocol: sftp
    host: 192.168.172.181
    port: 22
    # 用户名
    username: root
    # 密码
    password: 123456
    # 根路径
    root: /home/sftp1/
    sessionStrictHostKeyChecking: no
    # session连接超时时间
    sessionConnectTimeout: 15000
    # channel连接超时时间
    channelConnectedTimeout: 15000
#============================================================================
# sftp2  填写自己服务器信息
#============================================================================
sftp2:
  client:
    protocol: sftp
    host: 192.168.172.182
    port: 22
    # 用户名
    username: root
    # 密码
    password: 123456
    # 根路径
    root: /home/sftp2/
    sessionStrictHostKeyChecking: no
    # session连接超时时间
    sessionConnectTimeout: 15000
    # channel连接超时时间
    channelConnectedTimeout: 15000

SftpUtil类

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.deltapath.entity.SftpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.InputStream;

@Slf4j
@Component
public class SftpUtil {

    @Autowired
    public SftpProperties config;

    // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
    public static final String SESSION_CONFIG_STRICT_HOST_KEY_CHECKING = "StrictHostKeyChecking";


    /**
     * 创建SFTP连接
     *
     * @return
     * @throws Exception
     */
    public ChannelSftp createSftp() throws Exception {
        JSch jsch = new JSch();
        log.info("Try to connect sftp[" + config.getUsername() + "@" + config.getHost() + "], use password[" + config.getPassword() + "]");

        Session session = createSession(jsch, config.getHost(), config.getUsername(), config.getPort());
        session.setPassword(config.getPassword());
        session.connect(config.getSessionConnectTimeout());

        log.info("Session connected to {}.", config.getHost());

        Channel channel = session.openChannel(config.getProtocol());
        channel.connect(config.getChannelConnectedTimeout());

        log.info("Channel created to {}.", config.getHost());

        return (ChannelSftp) channel;
    }

    /**
     * 创建session
     *
     * @param jsch
     * @param host
     * @param username
     * @param port
     * @return
     * @throws Exception
     */
    public Session createSession(JSch jsch, String host, String username, Integer port) throws Exception {
        Session session = null;

        if (port <= 0) {
            session = jsch.getSession(username, host);
        } else {
            session = jsch.getSession(username, host, port);
        }

        if (session == null) {
            throw new Exception(host + " session is null");
        }

        session.setConfig(SESSION_CONFIG_STRICT_HOST_KEY_CHECKING, config.getSessionStrictHostKeyChecking());
        return session;
    }

    /**
     * 关闭连接
     *
     * @param sftp
     */
    public void disconnect(ChannelSftp sftp) {
        try {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                } else if (sftp.isClosed()) {
                    log.info("sftp is closed already");
                }
                if (null != sftp.getSession()) {
                    sftp.getSession().disconnect();
                }
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }


    public boolean uploadFile(String targetPath, InputStream inputStream, String fileName) throws Exception {
        ChannelSftp sftp = this.createSftp();
        try {
            sftp.cd(config.getRoot());
            log.info("Change path to {}", config.getRoot());

         /*  // 这里
            int index = targetPath.lastIndexOf("/");
            String fileDir = targetPath.substring(0, index);
            String fileName = targetPath.substring(index + 1);
            boolean dirs = this.createDirs(fileDir, sftp);
            if (!dirs) {
                log.error("Remote path error. path:{}", targetPath);
                throw new Exception("Upload File failure");
            }*/
            sftp.put(inputStream, fileName);
            return true;
        } catch (Exception e) {
            log.error("Upload file failure. TargetPath: {}", targetPath, e);
            throw new Exception("Upload File failure");
        } finally {
            this.disconnect(sftp);
        }
    }


}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值