package com.test;
import cn.hutool.core.util.StrUtil;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* 需引入 com.jcraft.jsch
* <dependency>
* <groupId>com.jcraft</groupId>
* <artifactId>jsch</artifactId>
* <version>0.1.55</version>
* </dependency>
* @author jojo
* @version 1.0
* @date 2022/8/16 14:21
*/
@Slf4j
public class SFTPUtil {
private static final String FTP_HOST = "127.0.0.1";
private static final String FTP_USERNAME = "username";
private static final String FTP_PASSWORD = "passwrod";
private static final String DOWNLOAD_PATH = "/home/test";
/**
* @param remoteDir 远程目录
* @return
*/
public Map<String, File> downFile(String remoteDir) {
File directory = new File(DOWNLOAD_PATH + remoteDir);
if (!directory.exists()) {
directory.mkdirs();
}
Map<String, File> fileMap = new HashMap<>(20);
if (StrUtil.isEmpty(remoteDir)) {
return fileMap;
}
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
Session sshSession = jsch.getSession(FTP_USERNAME, FTP_HOST, 22);
sshSession.setPassword(FTP_PASSWORD);
Properties sshConfig = new Properties();
//当第一次连接服务器时,自动接受新的公钥
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
//ls命令获取文件名列表
Vector vector = channelSftp.ls(remoteDir);
log.info("文件数量:" + vector.size());
Iterator iterator = vector.iterator();
while (iterator.hasNext()) {
ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
//文件名称
String fileName = file.getFilename();
log.info("fileName=" + fileName);
if (!(".".equals(fileName)) && !("..".equals(fileName))) {
//todo 这里可使用if或正则不下载一些文件
InputStream inputStream = channelSftp.get(remoteDir + fileName);
if (inputStream != null) {
File newFile = new File(DOWNLOAD_PATH + remoteDir + fileName);
//将InputStream转File
copyToFile(inputStream, newFile);
fileMap.put(fileName, newFile);
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.exit();
}
}
return fileMap;
}
private static void copyToFile(InputStream inputStream, File file)
throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
// commons-io
//IOUtils.copy(inputStream, outputStream);
}
}
}