<dependency>
<groupId>com.jcraftgroupId>
<artifactId>jschartifactId>
<version>0.1.54version>
dependency>
代码
package com.info.provincial.utils;
import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
/**
* @ClassName Sftps1
* @Description TODO
* @Date DATE{TIME}
* @Version 1.0
*/
public class SFTPSUtil {
private static final Logger log = LoggerFactory.getLogger(SFTPSUtil.class);
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);
}
/**
* 断开连接
*
* @throws Exception
*/
public void disconnect() throws Exception {
try {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
} else if (this.sftp.isClosed()) {
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new Exception("关闭sftp连接失败");
}
try {
if (this.sftp.getSession() != null) {
if (this.sftp.getSession().isConnected()) {
this.sftp.getSession().disconnect();
}
}
} catch (JSchException e) {
log.error(e.getMessage(), e);
}
}
/**
* 上传文件
*
* @param directory 上传的目录
* @param uploadFile 要上传的文件
*/
public void upload(String directory, String uploadFile) throws Exception {
sftp.cd(directory);
File file = new File(uploadFile);
FileInputStream fileInputStream = new FileInputStream(file);
sftp.put(fileInputStream, file.getName());
fileInputStream.close();
}
/**
* @param directory 上传FTPS地址
* @param file 文件
* @return void
* @Description //TODO 上传文件
* @Param
**/
public void upload(String directory, File file) throws Exception {
sftp.cd(directory);
FileInputStream fileInputStream = new FileInputStream(file);
sftp.put(fileInputStream, file.getName());
fileInputStream.close();
log.info("upload file " + file.getAbsolutePath() + " to host " + sshSession.getHost());
}
/**
* @param inputStream 文件流
* @param directory FTPS目标地址
* @param fileName 文件名称设置
* @return void
* @Description //TODO 文件流上传文件
* @Param
**/
public void uploadfileInputStream(FileInputStream inputStream, String directory, String fileName) throws Exception {
sftp.cd(directory);
sftp.put(inputStream, fileName);
}
/**
* @param src 文件
* @param dst 文件上传地址
* @param beforDay 时间文件夹20201102
* @return void
* @Description //TODO 上传文件并创建文件夹
**/
public void uploadDir(File src, String dst, String beforDay) throws Exception {
if (dst == null) {
//获取当前账号根目录
dst = sftp.getHome();
}
dst = dst + "/" + beforDay;
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(), beforDay);
}
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 {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
}
/**
* 下载文件
*
* @param directory
* @param downloadFile
* @param saveFile
* @throws Exception
*/
public void download(String directory, String downloadFile, File saveFile) throws Exception {
sftp.cd(directory);
FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
sftp.get(downloadFile, fileOutputStream);
fileOutputStream.close();
System.out.println("download file " + directory + "/" + downloadFile + " from host " + sshSession.getHost());
}
/**
* 下载文件
*
* @param src FTPS文件地址,可以是文件或文件夹,如果传NULL默认去当前账号根目录
* @param dst 本地储存地址new File("E:\test\outputfile\")
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void downloadDir(String src, File dst) throws Exception {
try {
//获取当前账号FTPS根目录
if (src == null) {
src = sftp.getHome();
}
sftp.cd(src);
} catch (Exception e) {
// TODO Auto-generated catch block
e.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.getFilename().startsWith(".")) {
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 删除路径,会删除本路径注意
* @return void
* @Description //TODO
* @Date 17:14 2020/11/2
* @Param
**/
public void deleteSFTP(String directory) {
try {
if (isDirExist(directory)) {
Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
if (vector.size() == 1) {
// 文件,直接删除
sftp.rm(directory);
} else if (vector.size() == 2) {
// 空文件夹,直接删除
sftp.rmdir(directory);
} else {
String fileName = "";
// 删除文件夹下所有文件
for (ChannelSftp.LsEntry en : vector) {
fileName = en.getFilename();
if (".".equals(fileName) || "..".equals(fileName)) {
continue;
} else {
deleteSFTP(directory + "/" + fileName);
}
}
// 删除文件夹
if (vector.size() > 1) {
sftp.rmdir(directory);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return java.util.List
* @Description //TODO 获取需要删除的文件路径
**/
public List<String> getDeletePath(String path) throws SftpException {
List<String> pathList = new ArrayList<>();
if (path == null) {
path = sftp.getHome();
}
Vector<ChannelSftp.LsEntry> vector = sftp.ls(path);
String fileName = "";
for (ChannelSftp.LsEntry en : vector) {
fileName = en.getFilename();
if (".".equals(fileName) || "..".equals(fileName)) {
continue;
} else {
pathList.add(path + "/" + fileName);
}
}
return pathList;
}
/**
* 351 * 判断目录是否存在
* 352 *
* 353 * @param directory
* 354 * @return
* 355
*/
public boolean isDirExist(String directory) {
try {
Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
if (null == vector) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
/**
* 列出目录下的文件
*
* @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;
}
/**
* @param args
* @return void
* @Description //TODO 上传数据包
**/
public static void main1(String[] args) throws Exception {
SFTPSUtil sftps = null;
try {
sftps = new SFTPSUtil();
//连接服务器
sftps.connect("130.140.150.66", 22, "shanghai", "pwd.1234");
//上传到服务器的位置
File file = new File("C:\\Users\\D\\Desktop\\测试.zip");
sftps.uploadfileInputStream(new FileInputStream(file), "/opt/ftp-root-dir/shanghai", "测试.zip");
} catch (Exception e) {
log.warn("", e);
} finally {
sftps.disconnect();
}
}
/**
* @param args
* @return void
* @Description //TODO 下载数据包
**/
public static void main2(String[] args) throws Exception {
SFTPSUtil sftps = null;
try {
sftps = new SFTPSUtil();
//连接服务器
sftps.connect("130.140.150.66", 22, "shanghai", "pwd.1234");
sftps.downloadDir(null, new File("E:\\test\\intputfile\\"));
} catch (Exception e) {
log.warn("", e);
} finally {
sftps.disconnect();
}
}
/**
* @param args
* @return void
* @Description //TODO 删除
* @Param
**/
public static void main(String[] args) throws Exception {
SFTPSUtil sftps = null;
try {
sftps = new SFTPSUtil();
//连接服务器
sftps.connect("130.140.150.66", 22, "shanghai", "pwd.1234");
List<String> deletePath2 = new ArrayList<>();
List<String> deletePath = sftps.getDeletePath(null);
for (String path : deletePath) {
List<String> deletePath1 = sftps.getDeletePath(path);
deletePath2.addAll(deletePath1);
}
for (String s : deletePath2) {
sftps.deleteSFTP(s);
}
} catch (Exception e) {
log.warn("", e);
} finally {
sftps.disconnect();
}
log.warn("删除成功");
}
}