From 3a499165df2060a2b2681ec1e866bcec0b2cd685 Mon Sep 17 00:00:00 2001 From: huangfeng Date: Wed, 25 Sep 2024 10:26:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0sftp=E5=B7=A5?= =?UTF-8?q?=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 ++ src/main/java/com/xydl/cac/util/SFTPTool.java | 73 +++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 src/main/java/com/xydl/cac/util/SFTPTool.java diff --git a/pom.xml b/pom.xml index c2c8b07..65af4ca 100644 --- a/pom.xml +++ b/pom.xml @@ -182,6 +182,11 @@ saaj-api 1.3.5 + + com.jcraft + jsch + 0.1.55 + diff --git a/src/main/java/com/xydl/cac/util/SFTPTool.java b/src/main/java/com/xydl/cac/util/SFTPTool.java new file mode 100644 index 0000000..f131423 --- /dev/null +++ b/src/main/java/com/xydl/cac/util/SFTPTool.java @@ -0,0 +1,73 @@ +package com.xydl.cac.util; + +import com.jcraft.jsch.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.io.*; +import java.util.Properties; +import java.util.Vector; + +@Component +@Slf4j +public class SFTPTool { + Session session = null; + ChannelSftp sftp = null; + + /** + * 1. 第一步:连接sftp服务器 + * + * @param host 主机 + * @param port 端口 + * @param username 用户名 + * @param password 密码 + * @return + */ + public void connect(String host, int port, String username, String password) throws JSchException { + JSch jsch = new JSch(); + session = jsch.getSession(username, host, port); + session.setPassword(password); + Properties sshConfig = new Properties(); + sshConfig.put("StrictHostKeyChecking", "no"); + session.setConfig(sshConfig); + session.connect(); + Channel channel = session.openChannel("sftp"); + channel.connect(); + sftp = (ChannelSftp) channel; + } + + /** + * 3.最后一步:关闭 channel和session + */ + public void disconnect() { + try { + if (sftp != null && sftp.isConnected()) { + sftp.disconnect(); + } + } catch (Exception ignore) { + } + try { + if (session != null && session.isConnected()) { + session.disconnect(); + } + } catch (Exception ignore) { + } + } + + public void upload(String localFilePath, String remoteFilePath) throws Exception { + sftp.put(new FileInputStream(localFilePath), remoteFilePath); + } + + public void download(String remoteFilePath, String localFilePath) throws Exception { + sftp.get(remoteFilePath, new FileOutputStream(localFilePath)); + } + + public void delete(String remoteFilePath) throws SftpException { + sftp.rm(remoteFilePath); + } + + public Vector listFiles(String remotePath) throws SftpException { + return sftp.ls(remotePath); + } + +}