SFTP上传文件,下载文件

SFTP上传文件,下载文件尝试
注意: 要在pom.xml中添加JSch 的依赖

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <!--<version>0.1.55</version>--> <!-- 不添加版本,默认最新版本 -->
</dependency>
  • 具体代码如下:
package com.xxx.xxx.xxxxxx.xxx.xxx;

import com.jcraft.jsch.*;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @author Liang
 * @version 1.0
 * @date 2022/5/24 9:39
 */
@Log4j2
public class SFTPPutFileTest {

    private static final String hostname = "xx.x.xxx.xxx"; // ip地址
    private static final String port = "22";  //端口号
    private static final String sshUser = "xxxxx"; //用户名
    private static final String sshPass = "xxxxxx"; // 密码

    /**
     * 上传文件
     * @throws Exception
     */
    @Test
    public void putFileToServer() throws Exception {

        File uploadFile = new File("/home/sftp/test.zip");// 要上传的文件

        JSch jSch = new JSch();
        String filePath = "/home/sftp/"; // 文件上传的地址
        Session session = null;
        ChannelSftp sftp = null;
        try {
            session = jSch.getSession(sshUser, hostname, Integer.parseInt(port));
            session.setPassword(sshPass);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no"); // 设置ssh安全级别
            session.setConfig(sshConfig); //设置参数
           session.connect(); //建立连接
            // 获取上传的管道
            Channel channel = session.openChannel("sftp");
            channel.connect(); // 建立sftp通道连接
            sftp = (ChannelSftp) channel;
            //发送文件、
            sftp.cd(filePath); //进入指定服务器目录 ,文件保存目录
            System.out.println("-------上传文件-------:"+ uploadFile);
            sftp.put(new FileInputStream(uploadFile), uploadFile.getName());  //读取要上传的文件并上传
            System.out.println("-------上传完成-------:"+ filePath);
        } catch (JSchException | FileNotFoundException | SftpException e){
            throw e;
        }
    }

    @Test
    public void downloadFile() throws Exception {
        String remotePath = "/home/sftp/test/"; //文件下载地址
        String localPath = "/home/sftp/"; // 文件保存地址
        getFileFromSFTP(remotePath, localPath, null, null, false);
    }

    /**
     *
     * @param remotePath 远程路径
     * @param localPath  本地路劲(本地文件存在)
     * @param fileFormat 下载文件格式(以特定字符开头,为空不做检验)
     * @param fileEndFormat 下载文件格式(文件格式,为空不做检验)
     * @param del 下载后是否删除sftp文件
     * @throws Exception
     */
    public void getFileFromSFTP(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) throws Exception {
        String hostName = "xx.x.xxx.xxx";
        String port = "22"; //
        String userName = "xxxxxx";
        String passWord = "xxxxxxxx";

        Session session = null;
        ChannelSftp channelSftp = null;
        List<String> filenames = new ArrayList<>();
        try {
            session = getSession(hostName, Integer.parseInt(port), userName, passWord);
//            Properties sshConfig = new Properties();
//            sshConfig.put("StrictHostKeyChecking", "no");
//            session.setConfig(sshConfig);
//            session.connect();
            // 获取管道
            Channel channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            //列出所有文件
            Vector ls = channelSftp.ls(remotePath); //列出远程目录中的文件
            if (ls.size() > 0) {
                log.info("本次处理文件个数不为零,开始下载...fileSize={}", ls.size()-2);
                Iterator<?> it = ls.iterator();
                while (it.hasNext()) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next(); //文件服务器目录中的文件
                    String filename = entry.getFilename(); //文件名字
                    SftpATTRS attrs = entry.getAttrs();
                    if(".".equals(filename) || "..".equals(filename)) {
                        continue;
                    }

                    if (!attrs.isDir()) {
                        boolean flag;
                        String localFileName = localPath + filename;
                        fileFormat = fileFormat == null ? "" : fileFormat.trim(); //文件格式
                        fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();

                        if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
                            if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
                                flag = getFile(session, remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        channelSftp.rm(remotePath + filename);
                                    }
                                }
                            }
                        } else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
                            if (filename.startsWith(fileFormat)) {
//                                flag = downloadFile(remotePath, filename, localPath, filename); //下载文件
                                flag = getFile(session, remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        channelSftp.rm(remotePath + filename);
                                    }
                                }
                            }
                        } else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
                            if (filename.endsWith(fileEndFormat)) {
                                flag = getFile(session, remotePath, filename, localPath, filename);
                                if (flag) {
                                    filenames.add(localFileName);
                                    if (flag && del) {
                                        //删除文件
                                        channelSftp.rm(remotePath + filename);
                                    }
                                }
                            }
                        } else {
                            flag = getFile(session,remotePath ,filename, localPath ,filename);
                            if (flag) {
                                filenames.add(localFileName);
                                if (flag && del) {
                                    channelSftp.rm(remotePath + filename);
                                }
                            }
                        }
                    } else {
                        //是个文件夹
                        String newRemotePath = remotePath+ filename+ "/";
                        String newLocalPath = localPath+ filename+ "\\";
                        File fi = new File(newLocalPath);
                        if(!fi.exists()) {
                            fi.mkdirs();
                        }
//                        batchDownLoadFile(newRemotePath, newLocalPath);
                        getFileFromSFTP(newRemotePath, newLocalPath, null, null, false);
                    }
                }
            }
        } catch (Exception e) {
            log.error("登录到服务器失败: {}", e.getMessage(), e);
            throw e;
        } finally {
            if (null != channelSftp){
                try {
                    channelSftp.disconnect();
                }catch (Exception e){}
            }
            if (null != session){
                try {
                    session.disconnect();
                }catch (Exception e){}
            }
        }
    }

    /**
     *
     * @param session
     * @param remotePath 远程文件地址
     * @param remoteFileName 远程文件名字
     * @param localPath 本地文件地址
     * @param localFileName 本地文件名字
     * @return
     * @throws Exception
     */
    public boolean  getFile(Session session, String remotePath, String remoteFileName ,String localPath, String localFileName) throws Exception{
        ChannelSftp sftp = null;
        FileOutputStream fileOutput = null;
        try{
            sftp = (ChannelSftp) session.openChannel("sftp");
            sftp.connect();
            File file = new File(localPath + localFileName);
            File path = new File(localPath);
            if(!path.exists()) {
                path.mkdirs();
            }
            fileOutput = new FileOutputStream(file);
            sftp.get(remotePath + remoteFileName,fileOutput);
            return true;
        }catch (Exception e){
            log.error("文件下载失败: {}",e.getMessage(),e);
            throw e;
        } finally {
            if (null != fileOutput){
                try {
                    fileOutput.close();
                }catch (Exception e){}
            }
        }
    }


    /**
     * 登录到指定服务器
     * @param sshHost
     * @param sshPort
     * @param sshUser
     * @param sshPass
     * @return
     * @throws JSchException
     */
    public Session getSession(String sshHost, int sshPort, String sshUser, String sshPass) throws JSchException {
        JSch jSch = new JSch();
        Session session = null;
        try{
            session = jSch.getSession(sshUser,sshHost,sshPort);
            session.setConfig("StrictHostKeyChecking","no");
            session.setPassword(sshPass);
            session.setTimeout(60000);
            session.connect();
            log.info("登录到{}的SFTP服务器成功!",sshHost);
        }catch (JSchException e){
            log.error("登录到服务器失败: {}",e.getMessage(),e);
            throw e;
        }
        return session;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值