package com.jttech.pfcs.util;
|
|
import java.io.*;
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.Vector;
|
|
import com.jcraft.jsch.ChannelSftp;
|
import com.jcraft.jsch.JSch;
|
import com.jcraft.jsch.Session;
|
import com.jcraft.jsch.SftpException;
|
|
/**
|
* sftp
|
*
|
* @author: yan xu
|
* @version: 1.0, 2017年12月21日
|
*/
|
public class SftpUtil {
|
|
public static Session getSession(String pIp, String pUser, String pPsw, int pPort) throws Exception {
|
Session session = null;
|
JSch jsch = new JSch();
|
if (pPort <= 0) {
|
// 连接服务器,采用默认端口
|
session = jsch.getSession(pUser, pIp);
|
} else {
|
// 采用指定的端口连接服务器
|
session = jsch.getSession(pUser, pIp, pPort);
|
}
|
// 设置登陆主机的密码
|
session.setPassword(pPsw);// 设置密码
|
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
|
session.setConfig("StrictHostKeyChecking", "no");
|
// 设置登陆超时时间
|
session.connect(300000);
|
return session;
|
}
|
|
|
|
public static ChannelSftp openChannel(Session pSession) throws Exception {
|
ChannelSftp channel = (ChannelSftp) pSession.openChannel("sftp");
|
channel.connect(10000000);
|
return channel;
|
}
|
|
|
|
public static void cd(ChannelSftp pSftp, String pPath) throws Exception {
|
String[] folders = pPath.split("/");
|
boolean isFirst = true;
|
for (int i = 0; i < folders.length; i++) {
|
String folder = folders[i];
|
if (folder == null || folder.length() == 0) {
|
continue;
|
}
|
if (isFirst) {
|
folder = "/" + folder;
|
isFirst = false;
|
}
|
try {
|
pSftp.cd(folder);
|
} catch (SftpException e) {
|
pSftp.mkdir(folder);
|
pSftp.cd(folder);
|
}
|
}
|
}
|
|
|
public static void put(ChannelSftp pSftp, byte[] pFileBytes, String pPath) throws Exception {
|
InputStream inputs = new ByteArrayInputStream(pFileBytes);
|
pSftp.put(inputs, pPath);
|
}
|
|
public static void put(ChannelSftp pSftp, File pFile, String pPath) throws Exception {
|
FileInputStream inputStream = new FileInputStream(pFile);
|
try {
|
pSftp.put(inputStream, pPath);
|
} finally {
|
inputStream.close();
|
}
|
}
|
|
|
|
public static void get(ChannelSftp pSftp, String pDownloadFile, String pSaveDirectory) throws Exception {
|
File dir = new File(pSaveDirectory);
|
if (!dir.exists()) {
|
dir.mkdirs();
|
}
|
String saveFile = pSaveDirectory + "/" + pDownloadFile;
|
File file = new File(saveFile);
|
FileOutputStream fileOutputStream = new FileOutputStream(file);
|
pSftp.get(pDownloadFile, fileOutputStream);
|
fileOutputStream.close();
|
}
|
|
|
|
public static List<String> listFiles(ChannelSftp pSftp, String pPath) throws Exception {
|
List<String> result = new ArrayList<>();
|
Vector ls = pSftp.ls(pPath);
|
if (null != ls && ls.size() > 0) {
|
for (Object l : ls) {
|
ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) l;
|
String filename = lsEntry.getFilename();
|
result.add(filename);
|
}
|
}
|
return result;
|
}
|
|
}
|