欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java利用jsch实现sftp上传一个目录下的所有文件到Linux服务器

程序员文章站 2023-12-28 22:06:58
...

需要依赖的jar包:Jsch-0.1.54.jar,hamcrest-all-1.3.jar

在maven中添加依赖

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-all -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

实现代码

package com.test;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.SftpProgressMonitor;

import java.io.File;

public class SftpUtil {

    private SftpUtil() {
    }

    public static void uploadFilesToServer(String srcPath, String dst, SftpProgressMonitor monitor) throws Exception {
        ChannelSftp sftp = upload(srcPath, dst, monitor);
        if (sftp != null) {
            sftp.quit();
            sftp.disconnect();
            System.out.println(" SFTP disconnect successfully!");
        }
        ChannelSftpSingleton.getInstance().closeChannel();
    }


    private static ChannelSftp upload(String path, String dst, SftpProgressMonitor monitor) throws SftpException {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        ChannelSftp chSftp = null;
        try {
            chSftp = ChannelSftpSingleton.getInstance().getChannelSftp();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        if (chSftp == null) {
            return null;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length <= 0) {
                return null;
            }
            for (File f : files) {
                String fp = f.getAbsolutePath();
                if (f.isDirectory()) {
                    String mkdir = dst + "/" + f.getName();
                    try {
                        chSftp.cd(mkdir);
                    } catch (Exception e) {
                        chSftp.mkdir(mkdir);
                    }
                    upload(fp, mkdir, monitor);
                } else {
                    chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
                }
            }
        } else {
            String fp = file.getAbsolutePath();
            chSftp.put(fp, dst, monitor, ChannelSftp.OVERWRITE);
        }
        return chSftp;
    }

}
package com.test;

import com.jcraft.jsch.*;

import java.util.Properties;

public class ChannelSftpSingleton {

    private static ChannelSftpSingleton instance;
    private ChannelSftp channelSftp;
    private Session session;

    private ChannelSftpSingleton() {
    }

    public static ChannelSftpSingleton getInstance() {
        if (instance == null) {
            instance = new ChannelSftpSingleton();
        }
        return instance;
    }

    public ChannelSftp getChannelSftp() throws JSchException {
        if (channelSftp != null) {
            return channelSftp;
        }
        channelSftp = getChannel();
        return channelSftp;
    }

    /**
     * 断开SFTP Channel、Session连接
     *
     * @throws Exception
     */
    public void closeChannel() throws Exception {
        if (channelSftp != null) {
            channelSftp.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
        System.out.println("disconnected SFTP successfully!");
    }

    /**
     * 获得SFTP Channel
     *
     * @return ChannelSftp Instance
     * @throws JSchException
     */
    private ChannelSftp getChannel() throws JSchException {
        String host = "120.**.***.***";
        int port = 22;
        String userName = "root";
        String password = "123456";
        // 创建JSch对象
        JSch jsch = new JSch();
        // 根据用户名,主机ip,端口获取一个Session对象
        session = jsch.getSession(userName, host, port);
        // 设置密码
        session.setPassword(password);
        Properties configTemp = new Properties();
        configTemp.put("StrictHostKeyChecking", "no");
        // 为Session对象设置properties
        session.setConfig(configTemp);
        // 设置timeout时间
        session.setTimeout(60000);
        session.connect();
        // 通过Session建立链接
        // 打开SFTP通道
        Channel channel = session.openChannel("sftp");
        // 建立SFTP通道的连接
        channel.connect();
        System.out.println("Connected successfully to ftpHost = " + host + ",as ftpUserName = " + userName + ", returning: " + channel);
        return (ChannelSftp) channel;
    }
}

测试

        String src = "C:\\Users\\admin\\Desktop\\test";
        String dst = "/usr/local/src/test";
        try {
            SftpUtil.uploadFilesToServer(src, dst, new SftpProgressMonitor() {
                @Override
                public void init(int i, String src, String dst, long size) {
                    System.out.println("正在上传 " + src + " 到 " + dst + ",文件大小:" + (double) (size / 1024) + "kb");
                }

                @Override
                public boolean count(long l) {
                    return true;
                }

                @Override
                public void end() {
                    System.out.println("上传成功");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

亲测可以成功!
参考来自:https://blog.csdn.net/g5628907/article/details/78281864

上一篇:

下一篇: