java调用SFTP的实现过程

java调用SFTP的实现过程

1、引入pom依赖

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

2、封装工具类

(1)封装工具类

package com.xinghan.keysystem.util.sftp;

import com.alibaba.druid.util.StringUtils;
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

@Component
@Scope("prototype")
public class SftpRootHelper {

    private ChannelSftp sftp = null;

    private Session sshSession = null;
    @Value("${sftpHost}")
    public  String host;
    @Value("${sftpPort}")
    public  int port;


    @Value("${sftpNameRoot}")
    public  String usernameRoot;
    @Value("${sftpPasswordRoot}")
    public  String passwordRoot;

    public SftpRootHelper() {
        super();
    }

    public SftpRootHelper(String username, String password, String host, int port) {
        this.usernameRoot = username;
        this.passwordRoot = password;
        this.host = host;
        this.port = port;
    }

    /**
     * 连接sftp服务器
     *
     * @return ChannelSftp sftp连接实例
     */
    public ChannelSftp connect() {
        JSch jsch = new JSch();
        try {
            sshSession = jsch.getSession(usernameRoot, host, port);
            sshSession.setPassword(passwordRoot);
            Properties properties = new Properties();
            properties.put("StrictHostKeyChecking", "no");
            properties.put("PreferredAuthentications", "password");
            sshSession.setConfig(properties);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (JSchException e) {
            throw new RuntimeException("sftp连接失败");
        }
        return sftp;
    }

    /**
     * 下载远程sftp服务器文件
     * @param remotePath     远程路径
     * @param remoteFilename 远程文件名称
     * @param localFilename  本地存放路径
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFilename, String localPath, String localFilename)
            throws SftpException, IOException, Exception {
        FileOutputStream output = null;
        boolean success = false;
        try {
            if (null != remotePath && remotePath.trim() != "") {
                sftp.cd(remotePath);
            }
            File targetFile = new File(localPath);// linux系统  mkdirPath 换成了win  C:\   D:\IDEA\img\job order
            targetFile.mkdirs();
            File localFile = new File(localPath + localFilename);
            // 有文件和下载文件重名
            if (localFile.exists()) {
                new File(localPath + localFilename).delete();
                System.err.println("文件: " + localPath + localFilename + " 已经存在!");
//                return success;
            }
            output = new FileOutputStream(localFile);
            String file = null;

            //遍历文件
            Vector remoteFilename1 = sftp.ls(remotePath);
            for (Object object : remoteFilename1) {
                ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                String filename = entry.getFilename();
                if (".".equals(filename) || "..".equals(filename)) {
                    continue;
                }
                if(filename.contains(remoteFilename)){
                    file=filename;
                    break;
                }
            }
            sftp.get(file, output);
            success = true;
            System.out.println("成功接收文件,本地路径:" + localPath + localFilename);
        } catch (SftpException e) {
            System.err.println("接收文件时有SftpException异常!");
            e.printStackTrace();
            return success;
        } catch (IOException e) {
            System.err.println("接收文件时有I/O异常!");
            System.err.println(e.getMessage());
            return success;
        } finally {
            try {
                if (null != output) {
                    output.close();
                }
                // 关闭连接
//                disconnect();
            } catch (IOException e) {
                System.err.println("关闭文件时出错!");
                System.err.println(e.getMessage());
            }
        }
        return success;
    }

    /**
     * 下载远程sftp服务器文件
     *
     * @param remotePath     远程路径
     * @param remoteFilename 远程文件名称
     * @param localFilename  本地存放路径
     * @return
     */
    public String downloadFileOPTK(String remotePath, String remoteFilename,String suffixName, String localPath, String localFilename)
            throws SftpException, IOException, Exception {
        FileOutputStream output = null;
        String success = "false";
        try {
            if (null != remotePath && remotePath.trim() != "") {
                sftp.cd(remotePath);
            }
            File targetFile = new File(localPath);// linux系统  mkdirPath 换成了win  C:\   D:\IDEA\img\job order
            targetFile.mkdirs();
            File localFile = new File(localPath + localFilename);
            // 有文件和下载文件重名
            if (localFile.exists()) {
                new File(localPath + localFilename).delete();
                System.err.println("文件: " + localPath + localFilename + " 已经存在!");
//                return success;
            }
            output = new FileOutputStream(localFile);
            String file = null;

            //遍历文件
            Vector remoteFilename1 = sftp.ls(remotePath);
            for (Object object : remoteFilename1) {
                ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                String filename = entry.getFilename();
                if (".".equals(filename) || "..".equals(filename)) {
                    continue;
                }
                //前缀判断是否相等
                if(filename.contains(remoteFilename)){
                    file=filename;
                    //后缀判断是否相等
                    if(file.contains(suffixName)){
                        file=filename;
                        break;
                    }
                }
            }
            sftp.get(file, output);
            success = file;//返回文件名称
            System.out.println("成功接收文件,本地路径:" + localPath + localFilename);
        } catch (SftpException e) {
            success="false";
            System.err.println("接收文件时有SftpException异常!");
            e.printStackTrace();
            return success;
        } catch (IOException e) {
            System.err.println("接收文件时有I/O异常!");
            System.err.println(e.getMessage());
            return success;
        } finally {
            try {
                if (null != output) {
                    output.close();
                }
                // 关闭连接
//                disconnect();
            } catch (IOException e) {
                System.err.println("关闭文件时出错!");
                System.err.println(e.getMessage());
            }
        }
        return success;
    }


    /**
     * 删除远程文件
     *
     * @param remotePath
     * @param remoteFilename
     * @return
     * @throws Exception
     */
    public boolean deleteFile(String remotePath, String remoteFilename) throws Exception {
        boolean success = false;
        try {
            // 更改服务器目录
            if (null != remotePath && remotePath.trim() != "") {
                sftp.cd(remotePath);
            }
            // 删除文件
            sftp.rm(remoteFilename);
            System.err.println("删除远程文件" + remoteFilename + "成功!");
            success = true;
        } catch (SftpException e) {
            System.err.println("删除文件时有SftpException异常!");
            e.printStackTrace();
            System.err.println(e.getMessage());
            return false;
        } catch (Exception e) {
            System.err.println("删除文件时有异常!");
            System.err.println(e.getMessage());
            return false;
        } finally {
            // 关闭连接
            disconnect();
        }
        return true;
    }

    /**
     * 上传单个文件,如果指正下载文件名则使用,否则保留原有文件名
     *
     * @param remoteFilePath 远程文件路径 /tmp/xxx.txt ||xxx.txt.zip
     * @param uploadFilePath 要上传的文件 如:D:\\test\\xxx.txt
     * @throws SftpException
     * @throws FileNotFoundException
     */
    public void uploadFile(String remoteFilePath, String uploadFilePath) throws SftpException, FileNotFoundException {
        FileInputStream in = null;
        connect();

        try {
            sftp.cd(remoteFilePath);
        } catch (SftpException e) {
            e.printStackTrace();
            try {
//                sftp.mkdir(remoteFilePath);
                String[] dirs = remoteFilePath.split("/");
                String tempPath = "";
                int index = 0;
                mkdirDir(dirs, tempPath, dirs.length, index);
                sftp.cd(remoteFilePath);
            } catch (SftpException e1) {
                e1.printStackTrace();
                disconnect();
                throw new RuntimeException("ftp创建文件路径失败" + remoteFilePath);
            }
        }
        File file = new File(uploadFilePath);
        try {
            in = new FileInputStream(file);
            sftp.put(in, file.getName());
        } catch (FileNotFoundException e) {
            throw e;
        } catch (SftpException e) {
            throw e;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            disconnect();
        }
    }

    /**
     * 递归根据路径创建文件夹
     *
     * @param dirs     根据 / 分隔后的数组文件夹名称
     * @param tempPath 拼接路径
     * @param length   文件夹的格式
     * @param index    数组下标
     * @return
     */
    public void mkdirDir(String[] dirs, String tempPath, int length, int index) {
        // 以"/a/b/c/d"为例按"/"分隔后,第0位是"";顾下标从1开始
        index++;
        if (index < length) {
            // 目录不存在,则创建文件夹
            tempPath += "/" + dirs[index];
        }
        try {
            sftp.cd(tempPath);
            if (index < length) {
                mkdirDir(dirs, tempPath, length, index);
            }
        } catch (SftpException ex) {
            try {
                sftp.mkdir(tempPath);
                sftp.cd(tempPath);
            } catch (SftpException e) {
                e.printStackTrace();


            }

            mkdirDir(dirs, tempPath, length, index);
        }
    }
    public void uploadFile(String remoteFilePath, InputStream inputStream, String FileName) throws SftpException {
        FileInputStream in = null;
        connect();

        if (inputStream == null) throw new NullPointerException();
        if (FileName == null || StringUtils.isEmpty(FileName)) throw new NullPointerException();

        try {
            sftp.cd(remoteFilePath);
        } catch (SftpException e) {
            e.printStackTrace();
            try {
                sftp.mkdir(remoteFilePath);
                sftp.cd(remoteFilePath);
            } catch (SftpException e1) {
                e1.printStackTrace();
                disconnect();
                throw new RuntimeException("ftp创建文件路径失败 : " + remoteFilePath);
            }
        }
        try {
            sftp.put(inputStream, FileName);
        } catch (SftpException e) {
            throw e;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }

        disconnect();
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
                this.sftp = null;
            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
                this.sshSession = null;
            }
        }
    }
}

(2)指定传输路径

package com.xinghan.keysystem.util.sftp;

/**
 * @program: keysystem-api
 * @description:
 * @author: ldb
 * @create: 2021-12-10 14:06
 */
public class SftpParam {
    //op-tk-pgp公钥
//    public static String OP_TK_PGP_FILE="/op_tk_file/";
//    //私钥、公钥、证书、CSR
//    public static String CARTIFICATE_FILE="/cartificate_file/";

//    //op-tk-pgp公钥
    public static String OP_TK_PGP_FILE = "/input/key/";

    //私钥、公钥、证书
    public static String CARTIFICATE_FILE = "/input/PKI/";
    //CSR
    public static String CSR_FILE = "/output/PKI/";
    //pgp公钥
    public static String PGP_KEY_FILE = "/output/key/pgp/";

    //
    public static String INPUT = "/input/";
    //
    public static String OUTPUT = "/output/";
}

标题3、配置文件加载协议信息,application.yml

##高安全区
sftpNameRoot: rdcenter
sftpPasswordRoot: Ftp666
sftpHost: 10.12.254.105
sftpPort: 22

4、调用方式

    //注入
    @Autowired
    private SftpRootHelper sftpRootHelper;
  /**
     * 修改
     */
    @RequestMapping("/synchronization")
    public void synchronization() throws Exception {
        //连接
        sftpRootHelper.connect();
         //sftp下载文件
        String path = sftpRootHelper.downloadFileOPTK("/"+ordClientCert.getFtp()+ SftpParam.INPUT,ordClientCert.getCustomName(),   ".csr",beas+ newPath,fileName + "p10");
        //delete sftp file
        sftpRootHelper.deleteFile("/"+ordClientCert.getFtp()+SftpParam.INPUT, path);
    }

你可能感兴趣的:(Java,java,开发语言)