【java】java sftp传输 ,java smb传输访问共享文件夹 集成springboot

news/2024/3/28 18:34:30/文章来源:https://blog.csdn.net/qq_36268103/article/details/129145888

文章目录

  • java的sftp传输
      • sftp注意事项
  • java smb传输
      • smb注意事项

tips: 集成springboot与不集成springboot区别不大,springboot中无非是引入一个maven依赖 加一个@Component注解 , 默认是单例;
复制代码前 请先认真看注意事项

java的sftp传输

依赖:

      <!-- sftp --><dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.49</version></dependency>

核心代码:


import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;@Slf4j
@Component
public class SftpUtils {private Session sshSession;private ChannelSftp sftp;/*** 连接sftp服务器** @param host* @param port* @param username* @param password* @return* @throws Exception*/public ChannelSftp connect(String host, int port, String username, String password) throws Exception {JSch jsch = new JSch();sshSession = jsch.getSession(username, host, port);log.debug("Session created.");sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();log.debug("Session connected.");log.debug("Opening Channel.");Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;log.debug("Connected to " + host + ".");return sftp;}/*** 连接sftp服务器** @param host* @param port* @param username* @param privateKey* @param passphrase* @return* @throws Exception*/public ChannelSftp connect(String host, int port, String username, String privateKey, String passphrase) throws Exception {JSch jsch = new JSch();//设置密钥和密码if (!StringUtils.isEmpty(privateKey)) {if (!StringUtils.isEmpty(passphrase)) {//设置带口令的密钥jsch.addIdentity(privateKey, passphrase);} else {//设置不带口令的密钥jsch.addIdentity(privateKey);}}sshSession = jsch.getSession(username, host, port);log.debug("Session created.");Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();log.debug("Session connected.");log.debug("Opening Channel.");Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;log.debug("Connected to " + host + ".");return sftp;}public void portForwardingL(int lport, String rhost, int rport) throws Exception {int assinged_port = sshSession.setPortForwardingL(lport, rhost, rport);System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);}/*** 断开连接*/public void disconnect() {if (sftp != null) sftp.disconnect();if (sshSession != null) sshSession.disconnect();}/*** 上传文件** @param directory  服务器的目录路径* @param uploadFile 要上传的文件路径*                   <p>*                   File path = new File(ResourceUtils.getURL("classpath:").getPath());*                   path.getAbsolutePath() : 相对路径 即class目录下*/public void upload(String directory, String uploadFile) throws Exception {sftp.cd(directory);File file = new File(uploadFile);sftp.put(new FileInputStream(file), file.getName());}/*** 上传文件** @param directory 服务器的目录路径* @param file      要上传的文件 例如 new File("Dockerfile") 是springboot项目根目录下的Dockerfile文件* @throws Exception*/public void upload(String directory, File file) throws Exception {sftp.cd(directory);sftp.put(new FileInputStream(file), file.getName());log.info("upload file " + file.getAbsolutePath() + " to host " + sshSession.getHost());}//利用流上传文件 fileNamepublic void uploadFileInputStream(MultipartFile file, String directory, String fileName) throws Exception {sftp.cd(directory);sftp.put(file.getInputStream(), fileName);}public void uploadDir(File src, String dst) throws Exception {if (!exist(dst)) {sftp.mkdir(dst);}if (src.isFile()) {upload(dst, src);} else {for (File file : src.listFiles()) {if (file.isDirectory()) {uploadDir(file, dst + "/" + file.getName());}upload(dst, file);}}}/*** 目录是否查找** @param path* @return* @throws SftpException*/public boolean exist(String path) throws SftpException {String pwd = sftp.pwd();try {sftp.cd(path);} catch (SftpException e) {if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {return false;} else {throw e;}} finally {sftp.cd(pwd);}return true;}/*** 下载文件** @param directory    服务器目录* @param downloadFile 要下载的文件名* @param saveFile     输出文件名* @throws Exception*/public void download(String directory, String downloadFile, String saveFile) throws Exception {try {sftp.cd(directory);File file = new File(saveFile);sftp.get(downloadFile, new FileOutputStream(file));} catch (SftpException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} finally {disconnect();}}/*** 下载文件** @param directory* @param downloadFile* @param saveFile* @throws Exception*/public void download(String directory, String downloadFile, File saveFile) throws Exception {try {sftp.cd(directory);sftp.get(downloadFile, new FileOutputStream(saveFile));System.out.println("download file " + directory + "/" + downloadFile + " from host " + sshSession.getHost());} catch (SftpException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} finally {disconnect();}}/*** 下载文件** @param src* @param dst* @throws Exception*/@SuppressWarnings("unchecked")public void downloadDir(String src, File dst) throws Exception {try {sftp.cd(src);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}dst.mkdirs();Vector<ChannelSftp.LsEntry> files = sftp.ls(src);for (ChannelSftp.LsEntry lsEntry : files) {if (lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) {continue;}if (lsEntry.getLongname().startsWith("d")) {downloadDir(src + "/" + lsEntry.getFilename(), new File(dst, lsEntry.getFilename()));} else {download(src, lsEntry.getFilename(), new File(dst, lsEntry.getFilename()));}}}/*** 删除文件** @param directory* @param deleteFile* @throws SftpException*/public void delete(String directory, String deleteFile) throws SftpException {sftp.cd(directory);sftp.rm(deleteFile);}/*** 列出目录下的文件** @param directory* @return* @throws SftpException*/public Vector listFiles(String directory) throws SftpException {return sftp.ls(directory);}public Session getSshSession() {return sshSession;}public ChannelSftp getSftp() {return sftp;}}

这个使用比较简单 也没有什么歧义 使用示例就不再写了


sftp注意事项

注: ftp和sftp是有区别的 ,linux中 ftp默认21端口 sftp默认是22端口,sftp传输加密 安全 所以效率较低,ftp传输不安全 所以效率较高, 本文讨论的是sftp 两种协议jar包引用不同。

java smb传输

依赖:

<!-- samba 共享文件夹 --><dependency><groupId>jcifs</groupId><artifactId>jcifs</artifactId><version>1.3.17</version></dependency>

简单封装了一个model类

model类代码:

/*** smb传输 model类* SMB地址写法:smb://用户名:密码@远程ip/地址/(或有无文件名)(注:如只获取文件夹后缀一定有“/”)* <p>*/
@Data
@EqualsAndHashCode
public class SMBConfig implements Serializable {/*** 服务器ip*/private String smbIp;/*** 服务器账号*/private String smbUser;/*** 服务器密码*/private String smbPwd;/*** 文件路径 在共享文件夹中的路径 (不带计算机名称)*/private String smbPath;/*** 文件名*/private String smbFile;/*** 输入流*/private InputStream is;/*** 输出流*/private OutputStream os;public SMBConfig() {}}

核心代码:


// import SMBConfig类路径;
import jcifs.UniAddress;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import java.io.*;@Component
@Slf4j
public class SMBUtils {/*** 往samba上传文件** @param url       服务器IP地址* @param userName  用户登录名* @param password  用户登录密码* @param storePath 服务器文件存储路径* @param fileName  服务器文件存储名称* @param is        文件输入流* @return true:上传成功* <p>* false:上传失败*/public static boolean storeFile(String url, String userName, String password, String storePath, String fileName, InputStream is) {BufferedInputStream bf = null;OutputStream os = null;boolean result = false;try {UniAddress ua = UniAddress.getByName(url);NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(url, userName, password);SmbSession.logon(ua, auth);SmbFile sf = new SmbFile("smb://" + url + storePath + "/" + fileName, auth);sf.connect();SmbFile sffolder = new SmbFile("smb://" + url + storePath, auth);if (!sffolder.exists())sffolder.mkdirs();bf = new BufferedInputStream(is);os = sf.getOutputStream();byte[] bt = new byte[1024];int n = bf.read(bt);while (n != -1) {os.write(bt, 0, n);os.flush();n = bf.read(bt);}result = true;} catch (Exception e) {log.error(e.getMessage(), e);} finally {try {if (bf != null)bf.close();if (os != null)os.close();} catch (IOException e) {log.error(e.getMessage(), e);}}return result;}/*** 从samba下载文件** @param url        服务器IP地址* @param userName   用户登录名* @param password   用户登录密码* @param remotePath 服务器文件存储路径* @param fileName   服务器文件存储名称* @param os         文件输出流* @return true:下载成功* <p>* false:下载失败*/public static boolean retrieveFile(String url, String userName, String password, String remotePath, String fileName, OutputStream os) {boolean result = false;BufferedInputStream bf = null;try {UniAddress ua = UniAddress.getByName(url);NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(url, userName, password);SmbSession.logon(ua, auth);SmbFile sf = new SmbFile("smb://" + url + remotePath + "/" + fileName, auth);if (sf.exists()) {bf = new BufferedInputStream(sf.getInputStream());byte[] bt = new byte[1024];int n = bf.read(bt);while (n != -1) {os.write(bt, 0, n);os.flush();n = bf.read(bt);}result = true;}} catch (Exception e) {log.error(e.getMessage(), e);} finally {try {if (bf != null)bf.close();if (os != null)os.close();} catch (IOException e) {log.error(e.getMessage(), e);}}return result;}/*** 从samba删除文件** @param url        服务器IP地址* @param userName   用户登录名* @param password   用户登录密码* @param remotePath 服务器文件存储路径* @param fileName   服务器文件存储名称* @return true:删除成功* <p>* false:删除失败*/public static boolean deleteFile(String url, String userName, String password, String remotePath, String fileName) {boolean result = false;try {UniAddress ua = UniAddress.getByName(url);NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(url, userName, password);SmbSession.logon(ua, auth);SmbFile sf = new SmbFile("smb://" + url + remotePath + "/" + fileName, auth);sf.delete();result = true;} catch (Exception e) {log.error(e.getMessage(), e);}return result;}/*** 往samba上传文件** @param smbConfig* @return*/public static boolean storeFile(SMBConfig smbConfig) {return storeFile(smbConfig.getSmbIp(), smbConfig.getSmbUser(), smbConfig.getSmbPwd(), smbConfig.getSmbPath(), smbConfig.getSmbFile(), smbConfig.getIs());}/*** 从samba下载文件** @param smbConfig* @return*/public static boolean retrieveFile(SMBConfig smbConfig) {return retrieveFile(smbConfig.getSmbIp(), smbConfig.getSmbUser(), smbConfig.getSmbPwd(), smbConfig.getSmbPath(), smbConfig.getSmbFile(), smbConfig.getOs());}}

使用示例:

	   SMBConfig smbConfig = new SMBConfig();smbConfig.setSmbIp("192.168.1.1");smbConfig.setSmbPwd("123456");smbConfig.setSmbUser("admin");// 路径smbConfig.setSmbPath("/test");// 上传后的文件名叫这个smbConfig.setSmbFile("pom");// 将springboot项目中根目录的pom.xml文件上传smbConfig.setIs(new FileInputStream("pom.xml"));// 上传storeFile(smbConfig);

注: smbPath 例如在共享文件夹中 路径为test 就写/test ,不用加上下图马赛克位置的计算机名
在这里插入图片描述

smb注意事项

smb1.0和2.0方式有差异 依赖也不同,本文是基于smb1.0协议的,需要windows服务器中开启,win10/win11中 在启用或关闭windows功能中开启
在这里插入图片描述

windows server中 在powerShell用命令开启:

 Set-SmbServerConfiguration -EnableSMB1Protocol $true

如果windows服务器没有账号密码,需要先设置;

如果共享功能没有开启 需要先开启
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_72265.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

网络安全态势感知研究综述

摘要&#xff1a;随着物联网、云计算和数字化的迅速发展&#xff0c;传统网络安全防护技术无法应对复杂的网络威胁。网络安全态势感知能够全面的对网络中各种活动进行辨识、理解和预测。首先分别对态势感知和网络安全态势感知的定义进行了归纳整理&#xff0c;介绍了网络安全态…

从0探索NLP——导航帖

从0探索NLP——导航帖 人工智能是一个定义宽泛、知识组成复杂的领域&#xff0c;而NLP是人工智能领域中的一类任务&#xff0c;他在哪呢&#xff1f;Emmmmm~不能说都有涉猎只能说全都都沾点&#xff1a; 每次想要针对NLP的某一点进行讲解时&#xff0c;不讲那写细枝末节&…

全链路压力测试

压力测试的目标&#xff1a; 探索线上系统流量承载极限&#xff0c;保障线上系统具备抗压能力 复制代码 如何做全链路压力测试&#xff1a; 全链路压力测试&#xff1a;整体步骤 容量洪峰 -》 容量评估 -》 问题发现 -》 容量规划 全链路压力测试&#xff1a;细化过程 整体目…

YOLOv6-3.0-目标检测论文解读

文章目录摘要算法2.1网络设计2.2Anchor辅助训练2.3自蒸馏实验消融实验结论论文&#xff1a; 《YOLOv6 v3.0: A Full-Scale Reloading 》github&#xff1a; https://github.com/meituan/YOLOv6上版本参考 YOLOv6摘要 YOLOv6 v3.0中YOLOv6-N达到37.5AP&#xff0c;1187FPS&…

linux下安装minio

获取 MinIO 下载 URL:访问&#xff1a;https://docs.min.io/ 一&#xff0c;进入/opt 目录&#xff0c;创建minio文件夹 cd /optmkdir minio二&#xff0c;wget下载安装包 wget https://dl.minio.io/server/minio/release/linux-amd64/minio三&#xff0c;进入minio文件夹创建…

如何使用 API 工具做 Websocket 测试

在 API 测试中&#xff0c;对 Websocket 协议的支持呼声越来越高&#xff0c;今天给大家推荐一款 开源的 API 管理工具——Postcat&#xff0c;以及教教大家&#xff0c;如何利用 API 管理工具做 Websocket 测试。 在线 Demo 链接&#xff1a;Postcat - Open Source API Ecosys…

广域网技术(PAP和CHAP)

第十六章&#xff1a;广域网技术 随着经济全球化与数字化变革加速&#xff0c;企业规模不断扩大&#xff0c;越来越多的分支机构出现在不同的地域。每个分支的网络被认为一个LAN&#xff08;Local Area Network&#xff0c;局域网&#xff09;&#xff0c;总部和各分支机构之间…

音频(九)——I2S 输出正弦波

I2S 输出正弦波 PC 端&#xff1a;先生成一个正弦波数组MCU 端&#xff1a;将正弦波数组使用 I2S 输出AP 端&#xff1a;接受从 MCU I2S 端口出来的正弦波数据并测量 THDN 等数据 PC 端生成正弦波数组 原理 三角函数的公式 yAsinxy AsinxyAsinx A 表示幅值 代码实现 源…

深入浅出C++ ——容器适配器

文章目录一、容器适配器二、deque类简介1. deque的原理2. deque迭代器3. deque的优点和缺陷4. 为什么选择deque作为stack和queue的底层默认容器一、容器适配器 适配器的概念 适配器是STL六大核心组件之一&#xff0c;它是一种设计模式&#xff0c;该种模式是将一个类的接口转换…

国家级高新区企业主要经济指标(2012-2021年)

数据来源&#xff1a;国家统计局 时间跨度&#xff1a;2012-2021 区域范围&#xff1a;全国&#xff08;及各分类统计指标&#xff09; 指标说明&#xff1a;手工提取最新的中国统计年鉴数据中各个excel指标表&#xff0c;形成各个指标文件的多年度数据&#xff0c;便于多年…

SpringBoot整合Spring Security过滤器链加载执行流程源码分析

文章目录1.引言2.Spring Security过滤器链加载1.2.注册名为 springSecurityFilterChain的过滤器2、查看 DelegatingFilterProxy类3.查看 FilterChainProxy类3.1 查看 doFilterInternal方法。3.2 查看 getFilters方法。4 查看 SecurityFilterChain接口5 查看 SpringBootWebSecur…

90%的人都理解错了HTTP中GET与POST的区别

Get和Post是HTTP请求的两种基本方法&#xff0c;要说它们的区别&#xff0c;接触过WEB开发的人都能说出一二。 最直观的区别就是Get把参数包含在URL中&#xff0c;Post通过request body传递参数。 你可能自己写过无数个Get和Post请求&#xff0c;或者已经看过很多权威网站总结…

制造企业为何要上数字化工厂系统?

以目前形势来看&#xff0c;数字化转型是制造企业生存的关键&#xff0c;而数字化工厂管理系统是一个综合性、系统性的工程&#xff0c;波及整个企业及其供应链生态系统。数字化工厂系统所要实现的互联互通系统集成、数据信息融合和产品全生命周期集成&#xff0c;将方方面面的…

国产真无线蓝牙耳机哪个好?国产半入耳蓝牙耳机推荐

近几年&#xff0c;生活中随处可见的有戴蓝牙耳机的人&#xff0c;而蓝牙耳机也因为使用更便捷、功能更先进受到了不少用户的喜爱。蓝牙耳机按照佩戴方式来划分&#xff0c;可以有入耳式、半入耳式、头戴式等。在此&#xff0c;我来给大家推荐几款国产半入耳蓝牙耳机&#xff0…

数字IC设计工程师是做什么的?

随着我国半导体产业的发展&#xff0c;近几年的新入行的从业人员&#xff0c;除了微电子相关专业的&#xff0c;还有就是物理、机械、数学、计算机等专业&#xff0c;很多人对这一高薪行业充满了好奇&#xff0c;那么数字IC设计工程师到底是做什么的&#xff1f; 首先来看看数…

每日一题——L1-069 胎压监测(15)

L1-069 胎压监测 分数 15 小轿车中有一个系统随时监测四个车轮的胎压&#xff0c;如果四轮胎压不是很平衡&#xff0c;则可能对行车造成严重的影响。 让我们把四个车轮 —— 左前轮、右前轮、右后轮、左后轮 —— 顺次编号为 1、2、3、4。本题就请你编写一个监测程序&#…

如何通过一台 iPhone 申请一个 icloud 邮箱账号 后缀为 @icloud.com

总目录 iOS开发笔记目录 从一无所知到入门 文章目录需求关键步骤步骤后续需求 在 iPhone 自带的邮箱软件中添加账号&#xff0c;排第一位的是 iCloud 邮箱&#xff1a; 选 iCloud 之后&#xff1a; 提示信息是exampleicloud.com&#xff0c;也就是说是有icloud.com为域的邮箱…

ElementUI--Dialog 弹框的使用

第一步&#xff1a;从官方文档中拷贝一个对话框到你的页面中 <el-dialog title"为中华民族之崛起而学习" :visible.sync"dialogVisible" width"30%" :fullscreen"false" :close-on-press-escape"false" show-close:close…

【蓝桥集训】第六天——递归

作者&#xff1a;指针不指南吗 专栏&#xff1a;Acwing 蓝桥集训每日一题 &#x1f43e;或许会很慢&#xff0c;但是不可以停下来&#x1f43e; 文章目录1.树的遍历2.递归求阶乘3.求斐波那契数列1.树的遍历 一个二叉树&#xff0c;树中每个节点的权值互不相同。 现在给出它的后…

人工智能基础部分13-LSTM网络:预测上证指数走势

大家好&#xff0c;我是微学AI&#xff0c;今天给大家介绍一下LSTM网络&#xff0c;主要运用于解决序列问题。 一、LSTM网络简单介绍 LSTM又称为&#xff1a;长短期记忆网络&#xff0c;它是一种特殊的 RNN。LSTM网络主要是为了解决长序列训练过程中的梯度消失和梯度爆炸问题…