Java远程主机下载文件,linux下载文件到本地服务器,scp、sftp方式文件下载

背景:有一个需求,需要从远程服务器,拉取文件到本地解析,然后存入es中。

2种方式文件下载,scp,sftp文件下载:

        1、scp方式文件下载
        2、sftp方式文件下载

sftp权限更容易获取一些,如果不知道使用哪种方式,推荐sftp

1、scp方式文件下载

引用jar包:

        <!--ssh-->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>

相关代码:


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 下载远程文件 到服务器本地
 */
@Slf4j
@Component
public class ScpSynFile {

    @Value("${synfile.ip}")
    private String IP;
    @Value("${synfile.port}")
    private int PORT;
    @Value("${synfile.user}")
    private String USER;
    @Value("${synfile.pwd}")
    private String PWD;

    /**
     * scp远程下载服务器文件
     *
     * @param sourceFilePath 远程文件路径
     * @param targetFilePath 本地文件路径
     * @param targetFileName 本地文件名称
     * @return
     */
    public boolean downloadFile(String sourceFilePath, String targetFilePath, String targetFileName) {
        boolean bool = false;
        FileOutputStream fos = null;
        try {
            log.info("==============下载远程文件 开始 :" + sourceFilePath);
            // 创建连接
            Connection conn = getConn();
            SCPClient scpClient = conn.createSCPClient();
            SCPInputStream scpis = scpClient.get(sourceFilePath);

            // 判断指定目录是否存在,不存在则先创建目录
            File file = new File(targetFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            // 下载文件
            fos = new FileOutputStream(targetFilePath + targetFileName);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = scpis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            bool = true;
            log.info("==============下载远程文件 结束 :" + sourceFilePath);
        } catch (Exception e) {
            log.error("==============下载远程文件 失败 :", e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioException) {
                    log.error("==============下载远程文件关闭文件输入流 失败 :", ioException);
                }
            }
        }

        return bool;
    }

    /**
     * 连接远程主机
     *
     * @return
     */
    public Connection getConn() {
        Connection conn = new Connection(IP, PORT);
        if (conn.isAuthenticationComplete()) {
            return conn;
        }
        try {
            log.info("========================开始连接远程主机");
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(USER, PWD);
            if (!isAuthenticated) {
                throw new Exception("authentication failed!");
            }
            return conn;
        } catch (Exception e) {
            log.error("========================主机连接失败 Connect error:", e);
        }
        return null;
    }

}


2、sftp方式文件下载

 引用jar包:

        <!--sftp-->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

相关代码:


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 下载远程文件 到服务器本地
 */
@Slf4j
@Component
public class SftpSynFile {

    @Value("${synfile.ip}")
    private String IP;
    @Value("${synfile.port}")
    private int PORT;
    @Value("${synfile.user}")
    private String USER;
    @Value("${synfile.pwd}")
    private String PWD;

    /**
     * Sftp下载单个文件
     *
     * @param sourceFilePath 远程文件路径
     * @param targetFilePath 本地文件路径
     * @param targetFileName 本地文件名称
     * @return
     */
    public boolean downloadFile(String sourceFilePath, String targetFilePath, String targetFileName) {
        FileOutputStream fieloutput = null;
        ChannelSftp sftp = null;
        try {
            // 创建连接
            sftp = getConn();

            // 判断指定目录是否存在,不存在则先创建目录
            File file = new File(targetFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            // 下载文件
            fieloutput = new FileOutputStream(targetFilePath + targetFileName);
            log.info("========================sftp下载单个文件开始:" + sourceFilePath);
            sftp.get(sourceFilePath, fieloutput);
            log.info("========================sftp下载单个文件结束:" + sourceFilePath);
            return true;
        } catch (Exception e) {
            log.error("========================sftp下载单个文件失败:", e);
        } finally {
            if (null != fieloutput) {
                try {
                    fieloutput.close();
                } catch (IOException e) {
                    log.error("========================FileOutputStream关闭失败:", e);
                }
            }
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
        }
        return false;
    }

    /**
     * sftp连接远程主机
     *
     * @return
     */
    public ChannelSftp getConn() {
        try {
            log.info("========================sftp连接远程主机开始");
            JSch jsch = new JSch();
            jsch.getSession(USER, IP, PORT);
            com.jcraft.jsch.Session sshSession = jsch.getSession(USER, IP, PORT);
            sshSession.setPassword(PWD);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            log.info("========================sftp连接远程主机结束");
            return (ChannelSftp) channel;
        } catch (Exception e) {
            log.error("========================sftp连接远程主机失败 Connect error:", e);
        }
        return null;
    }

}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值