本地服务器传输文件到远程服务器并执行copy命令

ChannelSftp sftpClient = JschSFTPUtils.getSftpClient(用户名, 密码, 端口号, ip);
        JschSFTPUtils.uploadFile(sftpClient,file.toString()这个是本地文件路径 , 远程服务器的目录);




 StringBuffer sqlbuffers = new StringBuffer();
        StringBuffer sqlbuffer = new StringBuffer();
        sqlbuffer.append("copy tazu.c_tazu_df_import");
        sqlbuffer.append(" from '");
        sqlbuffer.append("/home/gpadmin/dianfei/");
        sqlbuffer.append(file.getName());
        sqlbuffer.append("' WITH csv header delimiter '$' NULL '';");
        //上面的$符号时文件中的分隔符
        sqlbuffers.append(sqlbuffer.toString());

        if (StringUtils.isBlank(sqlbuffers.toString())) {
            throw new NullPointerException();
        }

        // 切换到管理员用户下来执行copy命令
        baseMapper.insertCTazuDfImport(sqlbuffers.toString());
/**    mapper文件中需要写的    **/
    @DataSource(DataSourceEnum.DB3)这个是需要切换的超级管理员账户
    void insertCTazuDfImport(String sql);
/**  mybatis中需要写的  **/
    <insert id="insertCTazuDfImport">
        ${_parameter}
    </insert>
package cc.mrbird.system.utils;

import com.jcraft.jsch.*;
import freemarker.log.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;

/**
 * @author:
 * @version: v1.0
 * @description: SFTP传输工具类 使用ssh登录服务器并上传下载文件
 * @date: 2021-06-08
 **/
public class JschSFTPUtils {

    private static final Logger log = Logger.getLogger(JschSFTPUtils.class.getName());
    /**
     * 连接sftp
     *
     * @param user
     * @param password
     * @param port
     * @param hostname
     * @return
     */
    public static ChannelSftp getSftpClient(String user, String password, int port, String hostname) {

        log.info("获取SFTP连接,正在连接服务器。。。。");
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession(user, hostname, port);
            if (password != null && password.length() > 0) {
                sshSession.setPassword(password);
            }
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // sshSession 记得关闭
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            log.info("连接服务器成功。。。。");
        } catch (JSchException e) {
            log.info("连接服务器失败。。。。");
        }
        return sftp;
    }


    /**
     * 检查文件是否存在
     *
     * @param sftp
     * @param filePath
     * @return
     */
    public static boolean checkExists(ChannelSftp sftp, String filePath) {

        boolean isExist = false;

        int index = filePath.lastIndexOf("/");
        String fileName = filePath.substring(index + 1);
        String parentDirPath = filePath.substring(0, index + 1);

        Vector files = null;
        try {
            files = listFiles(sftp, parentDirPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iterator = files.iterator();
        while (iterator.hasNext()) {
            ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) iterator.next();
            if (fileName.equals(lsEntry.getFilename())) {
                isExist = true;
                break;
            }
        }
        return isExist;
    }

    /**
     * 上传文件
     *
     * @param sftp
     * @param localFilePath
     * @param goalDirPath
     */
    public static void uploadFile(ChannelSftp sftp, String localFilePath, String goalDirPath) {
        try {
            // 判断目录是否存在
            if (!checkExists(sftp, goalDirPath)) {
                sftp.mkdir(goalDirPath);
            }
            sftp.cd(goalDirPath);
            File localFile = new File(localFilePath);
            String fileName = localFile.getName();
            sftp.put(new FileInputStream(localFile), fileName);
            log.info("上传文件成功,文件名:" + localFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传文件失败,文件名:" + localFilePath);
        }
    }


    /**
     * 上传文件
     *
     * @param sftp
     * @param localFilePath
     * @param goalDirPath
     */
    public static void upload(ChannelSftp sftp, String localFilePath, String goalDirPath) {
        try {
            sftp.cd(goalDirPath);
            File localFile = new File(localFilePath);
            String fileName = localFile.getName();
            sftp.put(new FileInputStream(localFile), fileName);
            log.info("上传文件成功,文件名:" + localFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传文件失败,文件名:" + localFilePath);
        }
    }


    /**
     * 获取目录下的所有文件
     *
     * @param sftp
     * @param dirPath
     * @return
     */
    public static Vector listFiles(ChannelSftp sftp, String dirPath) {

        Vector files = null;
        try {
            files = sftp.ls(dirPath);
        } catch (Exception e) {
            log.info("获取文件或目录失败。。。");
        }
        return files;
    }


    /**
     * 下载文件
     *
     * @param sftp
     * @param downloadFilePath
     * @param goalDirPath
     */
    public static void downloadFile(ChannelSftp sftp, String downloadFilePath, String goalDirPath) {
        try {
            if (checkExists(sftp, downloadFilePath)) {
                File downloadFile = new File(downloadFilePath);
                File goalFile = new File(goalDirPath, downloadFile.getName());
                FileOutputStream os = new FileOutputStream(goalFile);
                sftp.get(downloadFilePath, os);
            } else {
                log.info("文件【" + downloadFilePath + "】不存在~~");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param sftp
     * @param dirPath
     * @param filePath
     */
    public static void deleteFile(ChannelSftp sftp, String dirPath, String filePath) {
        try {
            sftp.cd(dirPath);
            sftp.rm(filePath);
        } catch (SftpException e) {
            e.printStackTrace();
        }

    }


    /**
     * 关闭sftp
     *
     * @param sftp
     */
    public static void close(ChannelSftp sftp) {
        try {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.getSession().disconnect();
                    sftp.disconnect();
                }
            }
        } catch (Exception e) {
            log.info("关闭sftp失败");
        }
        log.info("关闭sftp成功");
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值