java实现与远程 SFTP 服务器之间安全文件传输

2024-06-21 10:44

本文主要是介绍java实现与远程 SFTP 服务器之间安全文件传输,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 概要
    • FTP SFTP区别
    • 封装一个工具类

概要

SFTP(Secure File Transfer Protocol)是一种基于SSH(Secure Shell)协议的安全文件传输协议,它提供了在安全信道上进行数据传输的能力。相比传统的FTP(File Transfer Protocol),SFTP具有更高的安全性和更多的功能。

FTP SFTP区别

FTP和SFTP之间的一些主要区别:

特征FTPSFTP
协议基于传统的FTP协议(File Transfer Protocol)基于SSH的安全文件传输协议(Secure File Transfer Protocol)
安全性不安全,数据传输未加密安全,所有数据均经过SSH加密传输
端口默认端口为21默认端口为22
认证可以使用用户名和密码进行简单认证通过SSH密钥或用户名密码进行认证
加密不支持加密所有数据传输都通过SSH加密保护
目录访问控制依赖FTP服务器的权限和文件系统权限依赖SSH服务器的权限和文件系统权限
使用场景用于需要简单文件传输,无需考虑安全性的场景用于需要安全文件传输和操作的场景
适用性适用于内部网络和不涉及敏感信息的场景适用于需要加密和安全性要求较高的场景

封装一个工具类


import com.jcraft.jsch.*;import java.io.*;
import java.util.Properties;
import java.util.Vector;public class SftpUtil {public static final String NO_FILE = "No such file";public enum UploadStatus {Create_Directory_Fail,Create_Directory_Success,Upload_New_File_Success,Upload_New_File_Failed,File_Exits,Remote_Bigger_Local,Upload_From_Break_Success,Upload_From_Break_Failed,Delete_Remote_Faild;}private ChannelSftp sftp = null;private Session sshSession = null;private String username;private String password;private String host;private int port;public SftpUtil(String host, int port, String username, String password) {this.username = username;this.password = password;this.host = host;this.port = port;}/*** 连接到sftp服务器*/public ChannelSftp connect() throws Exception {JSch jsch = new JSch();try {jsch.getSession(username, host, port);sshSession = jsch.getSession(username, host, port);sshSession.setPassword(password);Properties properties = new Properties();properties.put("StrictHostKeyChecking", "no");sshSession.setConfig(properties);sshSession.connect();Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp)channel;} catch (JSchException e) {throw new Exception("FtpUtil-->connect异常" + e.getMessage());}return sftp;}/*** 关闭连接*/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;}}}/*** 上传文件* 用于将本地文件上传到指定的远程目录,并且使用给定的文件名。适用于将现有的本地文件上传到SFTP服务器的情况。** @param directory         远程上传目录* @param uploadFilePath    本地文件路径* @param fileName          远程文件名* @throws Exception        可能抛出的异常*/public void uploadFile(String directory, String uploadFilePath, String fileName) throws Exception {FileInputStream in = null;connect();try {sftp.cd(directory);} catch (SftpException e) {try {sftp.mkdir(directory);sftp.cd(directory);} catch (SftpException e1) {throw new Exception("ftp创建文件路径失败,路径为" + directory);}}File file = new File(uploadFilePath);try {in = new FileInputStream(file);sftp.put(in, fileName);} catch (FileNotFoundException e) {throw new Exception("文件不存在-->" + uploadFilePath);} catch (SftpException e) {throw new Exception("sftp异常-->" + e.getMessage());} finally {if (in != null) {try {in.close();} catch (IOException e) {throw new Exception("Close stream error." + e.getMessage());}}disconnect();}}/*** 上传文件* 将文件从一个输入流上传到指定的远程路径和文件名。适用于需要从内存中的输入流直接上传文件的情况。** @param filePath  远程文件路径* @param filename  文件名* @param in        输入流* @return          上传状态*/public UploadStatus uploadFile(String filePath, String filename, InputStream in) {try {sftp.put(in, filePath + filename, ChannelSftp.OVERWRITE);} catch (SftpException e) {e.printStackTrace();}return UploadStatus.Upload_From_Break_Success;}/*** 获取文件列表** @param filePath  远程文件路径* @return          文件列表*/public Vector<LsEntry> getFileList(String filePath) {Vector<LsEntry> list = new Vector<>();try {Vector veItem = sftp.ls(filePath);for (Object obj : veItem) {if (obj instanceof LsEntry) {list.add((LsEntry)obj);}}} catch (SftpException e) {e.printStackTrace();}return list;}/*** 下载文件** @param directory         远程下载目录* @param remoteFileName    远程文件名* @param localFile         本地文件路径* @return                  下载的文件对象* @throws Exception        可能抛出的异常*/public File downloadFile(String directory, String remoteFileName, String localFile) throws Exception {connect();File file = null;OutputStream output = null;try {file = new File(localFile);if (file.exists()) {file.delete();}file.createNewFile();sftp.cd(directory);output = new FileOutputStream(file);sftp.get(remoteFileName, output);} catch (SftpException e) {if (e.toString().equals(NO_FILE)) {throw new Exception("FtpUtil-->downloadFile--ftp下载文件失败" + directory + remoteFileName + "不存在");}throw new Exception("ftp目录或者文件异常,检查ftp目录和文件" + e.toString());} catch (FileNotFoundException e) {throw new Exception("本地目录异常,请检查" + file.getPath() + e.getMessage());} catch (IOException e) {throw new Exception("创建本地文件失败" + file.getPath() + e.getMessage());} finally {if (output != null) {try {output.close();} catch (IOException e) {throw new Exception("Close stream error." + e.getMessage());}}disconnect();}return file;}}

解释代码:

connect()函数:

  1. 创建 JSch 对象。
  2. 通过 getSession 方法获取会话,并设置用户名、主机、端口和密码。
  3. 创建属性对象,并将 StrictHostKeyChecking 设置为 no ,然后应用到会话配置中。
  4. 连接会话。
  5. 打开 sftp 通道并进行连接。
  6. 将通道强转为 ChannelSftp 类型并赋值给 sftp
  7. 最后返回 sftp 对象。

disconnect()函数:

  1. 检查 sftp 对象是否不为空且已连接,如果是,则断开连接并将其置为 null
  2. 检查 sshSession 对象是否不为空且已连接,如果是,则断开连接并将其置为 null

public void uploadFile(String directory, String uploadFilePath, String fileName) throws Exception {}方法:

  1. 调用 connect 方法建立连接。
  2. 尝试切换到指定的目录,如果目录不存在则创建目录后再切换。
  3. 读取要上传的文件,并通过 sftp.put 方法将文件上传。
  4. 处理可能出现的文件未找到、SFTP 异常等情况。
  5. finally 块中,若文件输入流不为空则关闭,并调用 disconnect 方法断开连接。

downloadFile函数:

  1. 调用 connect 方法建立连接。
  2. 创建本地文件,如果文件已存在则先删除再创建新文件。
  3. 切换到指定目录。
  4. 创建文件输出流。
  5. 通过 sftp.get 方法从远程获取文件并写入本地输出流。
  6. 处理可能出现的 SFTP 异常、文件未找到异常、本地目录异常、创建本地文件异常等情况。
  7. finally 块中,若输出流不为空则关闭,并调用 disconnect 方法断开连接。
  8. 最后返回下载的本地文件。

❤觉得有用的可以留个关注~❤

这篇关于java实现与远程 SFTP 服务器之间安全文件传输的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1081006

相关文章

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque