jsch包
jar包版本:jsch-0.1.54.jar
Sftp工具类
package com.jschpackage;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
public class Sftp {
private static Logger logger = LoggerFactory.getLogger(Sftp.class);
private static JSch jsch;
private static Session session;
private static Channel channel;
private static ChannelSftp channelSftp;
private static final Integer SFTP_DEFAULT_PORT = 22;
private static final Integer TIMEOUT = 60000;
private String sftpHost;
private String sftpUserName;
private String sftpPassword;
private int port;
/**
* 构造函数,端口22
* @param sftpHost IP
* @param sftpUserName 用户名
* @param sftpPassword 密码
*/
public Sftp(String sftpHost, String sftpUserName, String sftpPassword) {
this.sftpHost = sftpHost;
this.sftpUserName = sftpUserName;
this.sftpPassword = sftpPassword;
this.port = SFTP_DEFAULT_PORT;
}
/**
* 构造函数
* @param sftpHost IP
* @param sftpUserName 用户名
* @param sftpPassword 密码
* @param port 端口
*/
public Sftp(String sftpHost, String sftpUserName, String sftpPassword, int port) {
this.sftpHost = sftpHost;
this.sftpUserName = sftpUserName;
this.sftpPassword = sftpPassword;
this.port = port;
}
/**
* 模糊匹配某个文件名
* @param directory 匹配路径
* @param file 匹配字段
* @return
*/
public List<String> listFiles(String directory, String file) throws SftpException {
List<String> listFileName = new ArrayList<>();
long t1 = System.currentTimeMillis(); // 开始时间
initSession();
initChannelSftp();
try {
SftpATTRS lstat = channelSftp.lstat(directory);
lstat.isDir();
} catch (SftpException e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
listFileName.add("目录不存在!");
return listFileName;
}
}
ChannelSftp.LsEntrySelector selector = new ChannelSftp.LsEntrySelector() {
@Override
public int select(ChannelSftp.LsEntry lsEntry) {
// 文件名称(lsEntry中包含文件详细信息)
String filename = lsEntry.getFilename();
// 移除上级目录和根目录:"." ".."
if (".".equals(filename) || "..".equals(filename)) {
return CONTINUE;
}
// 匹配到的文件名add集合
if (filename.indexOf(file) > -1) {
listFileName.add(filename);
return CONTINUE;
}
return CONTINUE;
}
};
channelSftp.ls(directory, selector);
long t2 = System.currentTimeMillis(); // 结束时间
logger.info("匹配文件名花费时间:{}", t2 - t1, "ms");
close();
return listFileName;
}
/**
* 获取src目录下的文件详细信息
* @param directory 目录
* @return
*/
public Vector<?> vectorFiles(String directory) {
initSession();
initChannelSftp();
Vector<?> vector = null;
try {
SftpATTRS lstat = channelSftp.lstat(directory);
boolean dir = lstat.isDir();
vector = null;
if (dir) {
vector = channelSftp.ls(directory);
// 移除上级目录和根目录:"." ".."
vector.remove(0);
vector.remove(0);
}
} catch (SftpException e) {
logger.error("vectorFiles 异常!");
e.printStackTrace();
} finally {
close();
}
return vector;
}
/**
* cd目录
* @param directory 目录
*/
public void cdDirectory(String directory) throws SftpException {
initSession();
initChannelSftp();
channelSftp.cd(directory);
close();
}
/**
* 模糊匹配文件名下载文件
* @param directory 文件目录
* @param dst 目标地址
* @param file 文件名称
*/
public List<String> getFile(String directory, String dst, String file) throws SftpException {
initSession();
initChannelSftp();
channelSftp.cd(directory);
List<String> fileList = new ArrayList();
ChannelSftp.LsEntrySelector selector = new ChannelSftp.LsEntrySelector() {
@Override
public int select(ChannelSftp.LsEntry lsEntry) {
String filename = lsEntry.getFilename();
if (".".equals(filename) || "..".equals(filename)) {
return CONTINUE;
}
if (filename.indexOf(file) > -1) {
fileList.add(filename);
return CONTINUE;
}
return CONTINUE;
}
};
channelSftp.ls(directory, selector);
for (String getFilename : fileList) {
channelSftp.get(getFilename, dst);
logger.info("文件 {} {}", getFilename, "下载成功");
}
close();
return fileList;
}
/**
* 下载文件
* @param src 文件全路径
* @param dst 目的新地址
*/
public void getFile(String src, String dst) {
logger.info("连接sftp >>> 主机地址:{}", sftpHost);
initSession();
initChannelSftp();
logger.info("开始下载 >>> Download File: \"{}\" download to \"{}\"", src, dst);
try {
channelSftp.get(src, dst);
logger.info("结束下载 >>> Download File Success!");
} catch (SftpException e) {
logger.error("文件下载异常!", e);
e.printStackTrace();
} finally {
close();
}
}
/**
* 连接 ChannelSftp
* @throws JSchException
*/
private static void initChannelSftp() {
try {
channel = session.openChannel("sftp");
channel.connect(TIMEOUT); // 建立SFTP通道的连接
channelSftp = (ChannelSftp) channel;
logger.info("connect to ChannelSftp Success!");
} catch (JSchException e) {
logger.error("ChannelSftp 连接失败!");
e.printStackTrace();
}
}
/**
* 连接 Session
* @throws JSchException
*/
private void initSession() {
jsch = new JSch();
try {
session = jsch.getSession(sftpUserName, sftpHost, port);
session.setPassword(sftpPassword);
Properties config = new Properties();
// 优先使用 password 验证 注:session.connect()性能低,使用password验证可跳过gssapi认证,提升连接服务器速度
config.put("PreferredAuthentications", "password");
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(TIMEOUT);
logger.info("connect to Session Success!");
} catch (JSchException e) {
logger.error("Session 身份验证失败!");
e.printStackTrace();
}
}
/**
* 释放资源
*/
private static void close() {
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.quit();
}
if (channel != null && channel.isConnected()) {
channel.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
logger.info("close 释放资源 ");
}
}

浙公网安备 33010602011771号