feat: 增加sftp工具

dev
huangfeng 9 months ago
parent c1138109f4
commit 3a499165df

@ -182,6 +182,11 @@
<artifactId>saaj-api</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
</dependencies>
<build>

@ -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.: channelsession
*/
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);
}
}
Loading…
Cancel
Save