javasftp传输⽂件密码密钥⽅式package xxx.utils
import com.jcraft.jsch.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
SimpleDateFormat
//使⽤的是groovy
class SftpUtil {
private static final Logger logger = Class())
static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd")
JSch jsch = null
Session ssion = null
ChannelSftp channel = null
static ThreadLocal<SftpUtil> sftpLocal = new ThreadLocal<SftpUtil>()
SftpUtil(String urName, String host, int port, String password) {
connect(urName, host, port, password)
}
SftpUtil(String urName, String host, int port, String password, String keyFilePath, String passphra) {
connect(urName, host, port, password, keyFilePath, passphra)
}
boolean isConnected() {
return null != channel && channel.isConnected()
}
重庆大学城
static SftpUtil getSftpUtil(String urName, String host, int port, String password) throws Exception {
SftpUtil sftpUtils = ()
if (sftpUtils == null || !sftpUtils.isConnected()) {
sftpLocal.t(new SftpUtil(urName, host, port, password))
}
()
}
static SftpUtil getSftpUtil(String urName, String host, int port, String password, String keyFilePath, String passphra) throws Exception {
SftpUtil sftpUtils = ()
if (sftpUtils == null || !sftpUtils.isConnected()) {
sftpLocal.t(new SftpUtil(urName, host, port, password, keyFilePath, passphra))
}
()
}
static void relea() {
if (null != ()) {
<().clo()
sftpLocal.t(null)
}
}
/**
* 连接到指定的IP
*
* @throws JSchException
*/
ChannelSftp connect(String urName, String host, int port, String password) {
try {
jsch = new JSch()// 创建JSch对象
ssion = Session(urName, host, port)// 根据⽤户名、主机ip、端⼝号获取⼀个Session对象
ssion.tConfig("PreferredAuthentications", "password")
ssion.tPassword(password)
ssion.tConfig("StrictHostKeyChecking", "no")
ssion.tTimeout(60000)
ssion.tServerAliveInterval(2000)
ssion.tServerAliveCountMax(8)
logger.info("sftp ssion connected.")
channel = (ChannelSftp) ssion.openChannel("sftp")
上古神器4
logger.info("Connected successfully ${host} ${urName}")
} catch (JSchException e) {
<("sftp ", e)
}
}
/
**
* 密钥连接到指定的IP
*
* @throws JSchException
* @param keyFilePath 密钥路径
* @param passphra 密钥的密码
*/
public void connect(String urName, String host, int port, String password, String keyFilePath, String passphra) throws Exception {
try {
jsch = new JSch();
if (keyFilePath != null) {
if (passphra != null) {
jsch.addIdentity(keyFilePath, passphra);// 设置私钥
} el {
jsch.addIdentity(keyFilePath);// 设置私钥
}
logger.info("连接sftp,私钥⽂件路径:" + keyFilePath);
}
logger.info("SFTP Host: " + host + "; UrName:" + urName);
ssion = Session(urName, host, port);
logger.debug("Session 已建⽴.");
if (password != null) {
西装套裙
ssion.tPassword(password);
}
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
ssion.tConfig(sshConfig);
ssion.tConfig("kex", "diffie-hellman-group1-sha1");
logger.debug("Session 已连接.");
channel = (ChannelSftp) ssion.openChannel("sftp")
logger.info("连接到SFTP成功.Host: " + host);
} catch (Exception e) {
<("连接SFTP失败:", e);
}
}
/**
* 关闭连接
*/
void clo() {
if (channel != null) {
try {
channel.disconnect()
} catch (Exception e) {这个人
<("sftp clo ", e)
}
}
if (ssion != null) {
try {
ssion.disconnect()
} catch (Exception e) {
<("sftp clo ", e)
}
}
}
/**
* 执⾏相关的命令,
* 但是部分情况不可⽤
*
* @throws JSchException
失得
*/
String execCmd(String command) throws JSchException {
BufferedReader reader = null
String result = ""
if (channel == null) {
logger.info("SFTP服务器未连接")
return result
}
try {
if (command != null) {
((ChannelExec) channel).tCommand(command)
InputStream input = InputStream()
reader = new BufferedReader(new InputStreamReader(input))
String buf = null
while ((buf = adLine()) != null) {
logger.info(buf)
result += buf
}
}
} catch (IOException e) {
<("远程服务器端IO流错误:" + e.getMessage())
e.printStackTrace()
} catch (JSchException e) {
<("Jsch传输异常:" + e.getMessage())
e.printStackTrace()
} finally {
try {
reader.clo()
} catch (IOException e) {
<("远程服务器端IO流关闭失败:" + e.getMessage())
e.printStackTrace()
}
}
result
}
/**
* 上传⽂件
*
* @param fileName
* 上传的⽂件,含扩展名
* @param ftpPath
* ⽂件本地⽬录
* @param outFilePath
昨日的世界
* ⽂件上传⽬录
* @throws JSchException* @throws FileNotFoundException* 上传本地最新⽂件,并备份服务器端原⽂件 */
void upload(String fileName, String localPath, String outFilePath) throws Exception {
//连接sftp
if (channel == null) {
logger.info("SFTP服务器未连接")
relea()
return
}
String localFilepath = localPath + fileName
File localFile = new File(localFilepath)
FileInputStream input = null
try {
if (!ists()) {
logger.warn("本地服务器:上传⽂件不存在")
return
}
if (existFile(outFilePath, fileName)) {
return
}
String uploadFile = outFilePath + fileName //上传的⽂件
logger.info("上传⽂件:" + fileName + "开始")
input = new FileInputStream(localFile)
channel.put(input, uploadFile, ChannelSftp.OVERWRITE)
logger.info("上传到sftp成功")
//上传完成,备份本地⽂件
String localBak = bakFileName(fileName)
String bakPath = bakPath(localPath, fileName)
File newfile = new File(bakPath + localBak)
if (ameTo(newfile)) {
logger.info("本地⽂件备份成功:" + localBak)
} el {
logger.info("本地⽂件备份失败:" + localBak)
}
} catch (Exception e) {
logger.info("上传⽂件:" + fileName + "失败")
throw e
} finally {
if (input) {
input.clo()
}
relea()
}
}
/**
* 上传⽂件某⽂件夹下所有⽂件
*
* @param fileName
* 上传的⽂件,含扩展名
* @param ftpPath
* ⽂件本地⽬录
* @param outFilePath
* ⽂件上传⽬录
* @throws JSchException* @throws FileNotFoundException*
*/
void uploadAllFile(String fileName, String localPath, String outFilePath, String bakPath) throws Exception { //连接sftp
if (channel == null) {
logger.info("SFTP服务器未连接")
relea()
return
}
劳动最光荣绘画
File[] files = []
File localFile = new File(localPath)
FileInputStream input = null
List<FileInputStream> ins = []
try {
if (!ists()) {
logger.warn("本地服务器:上传⽂件不存在")
return
}
if (existFile(outFilePath, fileName)) {
return
}
if (localFile.isDirectory()) {
files = localFile.listFiles();
if (files == null || files.length <= 0) {
return;
}
for (File f : files) {
String uploadFile = outFilePath + f.getName() //上传的⽂件
logger.info("上传⽂件:" + f.getName() + "开始")
input = new FileInputStream(f)
ins.add(input)
channel.put(input, uploadFile, ChannelSftp.OVERWRITE)
logger.info("上传到sftp成功")
}
}
logger.info(files.size()+"---------------------------------------")
} catch (Exception e) {
logger.info("上传⽂件:" + fileName + "失败")
throw e
} finally {
ins?.each {it.clo()}
if (input) {
input.clo()
}
relea()
//上传完成,备份本地⽂件
if (bakPath) {
files?.each { it.renameTo(new File(bakPath+Name()))) }
} el {
files?.each {logger.info("删除⽂件:" + it.getName() + "--:"+it.delete())}
}
}
}
/**
* 下载⽂件
* 备份本地⽂件,再下载服务器端最新⽂件
* @param localPath 本地存放路径
* @param remotePath 服务器端存放路径
* @throws JSchException
*/
void download(String fileName, String localPath, String remotePath) throws Exception {
// src linux服务器⽂件地址,dst 本地存放地址
if (channel == null) {
logger.info("SFTP服务器未连接")
return
}
String remoteFile = remotePath + fileName
String localFile = localPath + fileName
FileOutputStream output =null
try {
if (!existFile(remotePath, fileName)) {
logger.warn("SFTP服务器:下载⽂件不存在" + remotePath + fileName)
return
}
File file = new File(localFile)
if (file.size() > 0) {
//创建新名字的抽象⽂件
String bakname = bakFileName(fileName)
String bakPath = bakPath(localPath, fileName)
File newfile = new File(bakPath + bakname)
if (ameTo(newfile)) {
logger.info("本地⽂件:" + fileName + "备份成功")
} el {
logger.info("本地⽂件:" + fileName + "备份失败,将覆盖原⽂件!")
}
}
output = new FileOutputStream(file)
logger.info("下载⽂件:" + fileName + "开始")
<(remoteFile, output)
logger.info("下载⽂件:" + fileName + "成功")
//下载完成后备份服务器⽂件
String bakFile = bakFileName(fileName)
String bakRemotePath = bakPath(remotePath, fileName)
//ame(remoteFile, bakRemotePath + fileName)
//delete(remotePath, fileName)
logger.info("服务器端⽂件备份成功:" + bakFile)
} catch (Exception e) {
logger.info("下载⽂件:" + fileName + "失败")
throw e
} finally {
if(output) {
output.clo()
}
relea()
}
}
/**
* 删除⽂件
*
* @param directory
* 要删除⽂件所在⽬录
* @param deleteFile
* 要删除的⽂件
* @throws JSchException
*/
void delete(String directory, String deleteFile) throws Exception {
if (channel == null) {
logger.info("SFTP服务器未连接")
return
}
channel.cd(directory)
<(deleteFile)
logger.info("删除成功")
}
/**
* 列出⽬录下的⽂件
*
* @param directory
* 要列出的⽬录
* @param sftp
* @return
* @throws JSchException
*/
@SuppressWarnings("rawtypes")
Vector listFiles(String directory) throws Exception {
if (channel == null) {
logger.info("SFTP服务器未连接")
return null
}
Vector vector = channel.ls(directory)
return vector
}
家庭功能/**
* 判断⽂件是否存在
* @param sourceName
* @return
*/
Boolean existFile(String remotrPath, String filename) {
Vector files = listFiles(remotrPath)
Boolean rst = fal
files.each {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it
if (Filename() == filename) {
rst = true
}
}
rst
}
String bakFileName(String sourceName) {
return sourceName + "." + df.format(new Date()) + System.currentTimeMillis().toString()
}
String bakPath(String outFilePath, String fileName) {
List<String> names = fileName.split(".csv").toList()
if (outFilePath.lastIndexOf("/") != -1) {
return outFilePath.substring(0, outFilePath.lastIndexOf("/"))+ "bak/"
} el if (outFilePath.lastIndexOf("\\") != -1) {
return outFilePath.substring(0, outFilePath.lastIndexOf("\\"))+ "bak\\"
}
return outFilePath + "bak/"
}
}
相关jar: com.jcraft:jsch:0.1.55
下载调⽤⽅式:
1 Respon downloadSftpFile(String fileName, String ftpPath, String outFilePath) {
2 Long startMill = new Date().getTime()
3//连接sftp
4try {
5 Map sftpApiMap = sftpApiSetting.sftpApiMap
6
7//通过密码
8 //SftpUtil(sftpApiMap.ftpUrName as String, sftpApiMap.ftpHost as String, sftpApiMap.ftpPort as int, sftpApiMap.ftpPassword as String).download(fileName, ftpPath, outFilePath)
9//通过私钥
10 SftpUtil(sftpApiMap.ftpUrName as String, sftpApiMap.ftpHost as String, sftpApi
Map.ftpPort as int, sftpApiMap.ftpPassword as String, sftpApiMap.keyFilePath as String, sftpApiMap.passphra as String).download(fileName
11 } catch (Exception e) {
12 e.printStackTrace()
13 responMessage = (null, outFilePath + fileName + "⽂件下载失败\n" + e.message)
14 }
15 Long endMill = new Date().getTime()
16 logger.info("SFTP:download 完成时间" + (endMill - startMill) / 1000)
17 }
上传调⽤:
Respon uploadSftpFile(String fileName, String ftpPath, String outFilePath, String bakPath) {
Long startMill = new Date().getTime()
//连接sftp
try {
Map sftpApiMap = sftpApiSetting.sftpApiMap
//通过密码
//SftpUtil(sftpApiMap.ftpUrName as String, sftpApiMap.ftpHost as String, sftpApiMap.ftpPort as int, sftpApiMap.ftpPassword as String).uploadAllFile(fileName, ftpPath, outFilePath, bakPath)
//通过私钥
SftpUtil(sftpApiMap.ftpUrName as String, sftpApiMap.ftpHost as String, sftpApiMap.ftpPort as int, sftpApiMap.ftpPassword as String, sftpApiMap.keyFilePath as String, sftpApiMap.passphra as String).uploadAllFile(fil } catch (Exception e) {
e.printStackTrace()
responMessage = (null, fileName + "⽂件上传失败\n" + e.message)
}
Long endMill = new Date().getTime()
logger.info("SFTP:upload 完成时间" + (endMill - startMill) / 1000)
}