java使用sftp下载远程服务器文件
使用的是springboot的项目,只是贴出主要配置与类,代码较长,可以先折叠:
参考:https://www.cnblogs.com/xyzq/p/7049369.html
操作工具类SftpUtils:
public class SftpUtils {
private static final Logger log = LoggerFactory.getLogger(DownLoadFTPService.class);
private String host;// 服务器连接ip
private String username;// 用户名
private String password;// 密码
private int port = 22;// 端口号
private ChannelSftp sftp = null;
private Session sshSession = null;
@Value("${sftpTimeOut:0}")
private int timeOut;
public SftpUtils() {
}
public SftpUtils(String host, int port, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
this.port = port;
}
public SftpUtils(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
}
/**
* 通过SFTP连接服务器
*/
public void connect() {
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
if (log.isInfoEnabled()) {
log.info("Session created.");
}
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
if(0 != timeOut) {
sshSession.setTimeout(timeOut);
}
sshSession.connect();
if (log.isInfoEnabled()) {
log.info("Session connected.");
}
Channel channel = sshSession.openChannel("sftp");
channel.connect();
if (log.isInfoEnabled()) {
log.info("Opening Channel.");
}
sftp = (ChannelSftp) channel;
if (log.isInfoEnabled()) {
log.info("Connected to " + host + ".");
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
if (log.isInfoEnabled()) {
log.info("sftp is closed already");
}
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
if (log.isInfoEnabled()) {
log.info("sshSession is closed already");
}
}
}
}
/**
* 批量下载文件
* @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\\Duansha\\sftp\\)
* @return
*/
public List<String> batchDownLoadFile(String remotePath, String localPath) {
return batchDownLoadFile(remotePath, localPath, null, null, false);
}
/**
* 批量下载文件
*
* @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\\Duansha\\sftp\\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式,为空不做检验)
* @param del:下载后是否删除sftp文件
* @return
*/
public List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat,
boolean del) {
List<String> filenames = new ArrayList<String>();
try {
// connect();
Vector<?> v = listFiles(remotePath);
// sftp.cd(remotePath);
if (v.size() > 0) {
//v.size()中包含(. 和 ..)所以实际文件数目=vize-2
log.info("本次处理文件个数不为零,开始下载...fileSize={}", v.size()-2);
Iterator<?> it = v.iterator();
while (it.hasNext()) {
LsEntry entry = (LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
log.info("filename: {} ", filename);
if(".".equals(filename) || "..".equals(filename)) {
continue;
}
if (!attrs.isDir()) {
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat.trim();
fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();
// 四种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
if (filename.startsWith(fileFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
if (filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
}else {
String newRemotePath = remotePath+ filename+ "/";
String newLocalPath = localPath+ filename+ "\\";
File fi = new File(newLocalPath);
if(!fi.exists()) {
fi.mkdirs();
}
log.info("newRemotePath:{}, newLocalPath:{}", newRemotePath, newLocalPath);
batchDownLoadFile(newRemotePath, newLocalPath);
}
}
}
if (log.isInfoEnabled()) {
log.info("download file is success:remotePath=" + remotePath + "and localPath=" + localPath
+ ",file size is" + (v.size()-2));
}
} catch (SftpException e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
// this.disconnect();
}
return filenames;
}
/**
* 批量下载文件
*
* @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\\Duansha\\sftp\\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式,为空不做检验)
* @param del:下载后是否删除sftp文件
* @return
*/
public List<String> batchDownLoadFileNotDir(String remotePath, String localPath, String fileFormat, String fileEndFormat,
boolean del) {
List<String> filenames = new ArrayList<String>();
try {
// connect();
Vector<?> v = listFiles(remotePath);
// sftp.cd(remotePath);
if (v.size() > 0) {
//v.size()中包含(. 和 ..)所以实际文件数目=vize-2
log.info("本次处理文件个数不为零,开始下载...fileSize={}", v.size()-2);
Iterator<?> it = v.iterator();
while (it.hasNext()) {
LsEntry entry = (LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
log.info("filename: {} ", filename);
if(".".equals(filename) || "..".equals(filename)) {
continue;
}
if (!attrs.isDir()) {
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat.trim();
fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();
// 四种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0) {
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) {
if (filename.startsWith(fileFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) {
if (filename.endsWith(fileEndFormat)) {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
} else {
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag) {
filenames.add(localFileName);
if (flag && del) {
deleteSFTP(remotePath, filename);
}
}
}
}else {
}
}
}
if (log.isInfoEnabled()) {
log.info("download file is success:remotePath=" + remotePath + "and localPath=" + localPath
+ ",file size is" + (v.size()-2));
}
} catch (SftpException e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
// this.disconnect();
}
return filenames;
}
/**
* 下载单个文件
*
* @param remotPath:远程下载目录(以路径符号结束)
* @param remoteFileName:下载文件名
* @param localPath:本地保存目录(以路径符号结束)
* @param localFileName:保存文件名
* @return
*/
public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileOutputStream fieloutput = null;
try {
// sftp.cd(remotePath);
File file = new File(localPath + localFileName);
File f = new File(localPath);
if(!f.exists()) f.mkdirs();
// if(!file.exists()) {
// file.createNewFile();
// }else {
// log.info("文件已经下载,不需要重复下载.");
// return true;
// }
fieloutput = new FileOutputStream(file);
sftp.get(remotePath + remoteFileName, fieloutput);
if (log.isInfoEnabled()) {
log.info("- - - - - DownloadFile: " + remoteFileName + " success from sftp.");
}
return true;
} catch (FileNotFoundException e) {
log.error(e.getMessage());
e.printStackTrace();
} catch (SftpException e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
if (null != fieloutput) {
try {
fieloutput.close();
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
}
return false;
}
/**
* 上传单个文件
*
* @param remotePath:远程保存目录
* @param remoteFileName:保存文件名
* @param localPath:本地上传目录(以路径符号结束)
* @param localFileName:上传的文件名
* @return
*/
public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileInputStream in = null;
try {
createDir(remotePath);
File file = new File(localPath + localFileName);
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
return true;
} catch (FileNotFoundException e) {
log.error(e.getMessage());
e.printStackTrace();
} catch (SftpException e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
}
return false;
}
/**
* 批量上传文件
*
* @param remotePath:远程保存目录
* @param localPath:本地上传目录(以路径符号结束)
* @param del:上传后是否删除本地文件
* @return
*/
public boolean bacthUploadFile(String remotePath, String localPath, boolean del) {
try {
connect();
File file = new File(localPath);
log.info("file: {} ", file);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile() && files[i].getName().indexOf("bak") == -1) {
if (this.uploadFile(remotePath, files[i].getName(), localPath, files[i].getName()) && del) {
deleteFile(localPath + files[i].getName());
}
}
}
if (log.isInfoEnabled()) {
log.info("upload file is success:remotePath=" + remotePath + "and localPath=" + localPath
+ ",file size is " + files.length);
}
return true;
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
this.disconnect();
}
return false;
}
/**
* 删除本地文件
*
* @param filePath
* @return
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
boolean rs = file.delete();
if (rs && log.isInfoEnabled()) {
log.info("delete file success from local.");
}
return rs;
}
/**
* 创建目录
*
* @param createpath
* @return
*/
public boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
this.sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
this.sftp.cd(createpath);
return true;
} catch (SftpException e) {
log.error(e.getMessage());
e.printStackTrace();
}
return false;
}
/**
* 判断目录是否存在
*
* @param directory
* @return
*/
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
log.error(e.getMessage());
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 删除stfp文件
*
* @param directory:要删除文件所在目录
* @param deleteFile:要删除的文件
* @param sftp
*/
public void deleteSFTP(String directory, String deleteFile) {
try {
// sftp.cd(directory);
sftp.rm(directory + deleteFile);
if (log.isInfoEnabled()) {
log.info("delete file success from sftp.");
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
/**
* 如果目录不存在就创建目录
*
* @param path
*/
public void mkdirs(String path) {
File f = new File(path);
String fs = f.getParent();
f = new File(fs);
if (!f.exists()) {
f.mkdirs();
}
}
/**
* 列出目录下的文件
*
* @param directory:要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector<?> listFiles(String directory) throws SftpException {
log.info("listFiles:{}",directory);
return sftp.ls(directory);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public ChannelSftp getSftp() {
return sftp;
}
public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
/** 测试 */
public static void main(String[] args) {
SftpUtils sftp = null;
// 本地存放地址
String localPath = "M:\\";
// Sftp下载路径
String sftpPath = "/usr/etc/";
try {
sftp = new SftpUtils("172.168.65.171", "root", "root1234");
sftp.connect();
// 下载
sftp.batchDownLoadFile(sftpPath, localPath, "error", null, false);
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
} finally {
sftp.disconnect();
}
}
/**
错误处理:
1. java.security.NoSuchAlgorithmException: DH KeyPairGenerator not available
复制sunjce_provider.jar(jre/lib/ext/)到lib下。
*/
}
SftpUtils.class
sftp实体SftpFileInfo:
使用:
配置文件配置:
#ip
sftpIpConfig: ip
#用户名
sftpUsernameConfig: xxx
#密码
sftpPasswordConfig: xxx
#远程服务器文件路径
remotePathConfig: /qq/ww/ee/
#远程服务器文件路径
remotePathConfig: /qq/ww/ee/
#本地保存路径
localPathConfig: D:\\
class中使用:
@Value("${sftpIpConfig:}")
private String sftpIpConfig;
@Value("${sftpUsernameConfig:}")
private String sftpUsernameConfig;
@Value("${sftpPasswordConfig:}")
private String sftpPasswordConfig;
@Value("${localPathConfig:}")
private String localPathConfig;
其中的配置也可以使用参数传入,如果配置固定不经常改的时候可以使用配置文件也比较方便。
使用sftpUtils:
SftpUtils sftp = null;
sftp = new SftpUtils(sftpFileInfo.getSftpIp(), sftpFileInfo.getSftpUsername(),sftpFileInfo.getSftpPassword());
sftp.connect();
之后的操作就是看实际情况,使用的都是SftpUtils.class中的方法了。
java使用sftp下载远程服务器文件的更多相关文章
- java通过sftp对linux服务器文件夹进行操作
本文主要讲sftp对linux服务器的文件和文件夹进行操作,windows server 服务器不支持. package com.lx.ftp; import java.io.File; import ...
- 在 Sublime Text 2 中使用 SFTP 插件快速编辑远程服务器文件
在 Sublime Text 2 中使用 SFTP 插件快速编辑远程服务器文件 开源程序 浏览:29555 2013年05月02日 文章目录[隐藏] 常见的工作流程 SFTP 安装和使用方法 第一步: ...
- 【实操日记】使用 PyQt5 设计下载远程服务器日志文件程序
最近通过 PyQt5 设计了一个下载服务器指定日期日志文件的程序,里面有些有意思的技术点,现在做一些分享. PyQt5 是一套 Python 绑定 Digia Qt5 应用的框架,是最强大的 GUI ...
- #在windows上使用ngix重定向目录访问远程服务器文件详细实例
为了在开发环境保持于生产环境相同的访问远程服务器文件资源的目录配置,需要在开发环境(windows)在远程文件服务器使用nignx重定向文件目录,因为网上的资料大都是copy的,解释比较笼统,也没有具 ...
- JCIFS读取远程服务器文件过慢的解决方法
JCIFS读取远程服务器文件过慢的解决方法 发表于3年前(2013-07-12 11:23) 阅读(1174) | 评论(0) // 我要收藏"; var favor_del = &qu ...
- 本地VSCode编辑远程服务器文件
前言 先说下我的场景:服务器搭设了一系列复杂环境,然后需要使用PHP实现某些功能 选这种远程编辑的原因: 首先PHP打死我也不想装(这个现在是出了VB外最惹人厌的语言了) 然后环境比较复杂,本地装下比 ...
- 如何使用sftp下载Linux服务器上的文件到本地
下载Linux服务器上的文件到本地 Linux服务器上的操作 sftp xxxxx@jumper.xxxx.com 使用put命令进行文件上传,put app.log 本地操作 sftp xxxxx@ ...
- java实现sftp客户端上传文件夹的功能
使用的jar: <dependencies> <dependency> <groupId>jsch</groupId> <artifactId&g ...
- 昔日埋雷不经意,今朝踩雷排查难:JetBrains系列IDE使用SFTP连接远程服务器报“EOF while reading packet”解决方法
写在前面 这是一篇问题解决记录.希望能帮到遇到同样问题的读者. 强烈建议:请您先看解决步骤一节,如果您发现在下的问题和您的问题不一样,就可以及时离开本文,避免浪费时间. 正文 问题描述 在使用GoLa ...
随机推荐
- mysql CMD命令窗连接 - 转载
cmd连接mysql的方法详解 首先需要进入mysql的安装文件夹bin目录下:cd + C:\Program Files\MySQL\MySQL Server 5.5\bin 连接:mysql -h ...
- 怎样发布一个工程到自己的GitHub
本人小白一枚: 第一次通过命令行的形式将自己的工程发布到自己的GitHub上去,还是请教了大神之后才完成的.通过总结经验,小白也掌握了一些关于往代码托管平台上发布工程的方式,其实只要用心学,里面的东西 ...
- centos7没有安装ifconfig命令的解决方法(转)
ifconfig命令是设置或显示网络接口的程序,可以显示出我们机器的网卡信息,可是有些时候最小化安装CentOS等Linux发行版的时候会默认不安装ifconfig等命令,这时候你进入终端,运行ifc ...
- XP_SP3_专业汉化版__x86_cd_x14-80404
1.镜像文件: zh-hans_windows_xp_professional_with_service_pack_3_x86_cd_x14-80404.iso 来自 msdn itellyou 2. ...
- 深入浅出TensorFlow(二):TensorFlow解决MNIST问题入门
2017年2月16日,Google正式对外发布Google TensorFlow 1.0版本,并保证本次的发布版本API接口完全满足生产环境稳定性要求.这是TensorFlow的一个重要里程碑,标志着 ...
- kolla all-in-one 安装
http://docs.openstack.org/developer/kolla/ 使用了Docker containers and Ansible playbooks 目前在Fedora/Ubun ...
- javascript HTML DOM 简单介绍
JavaScript HTML DOM通过 HTML DOM,可访问 JavaScript HTML 文档的所有元素.HTML DOM (文档对象模型)当网页被加载时,浏览器会创建页面的文档对象模型( ...
- LightOJ - 1341唯一分解定理
唯一分解定理 先分解面积,然后除2,再减去面积%长度==0的情况,注意毯子不能是正方形 #include<map> #include<set> #include<cmat ...
- STM32F407: USART 遇到的问题
今天初次使用STM32F407进行USART串口通讯实验,按照f103的代码写完了,发现没法发送数据, 查看文档后发现是由于没有将端口映射到USART1,然后添加如下代码: 1 GPIO_PinAFC ...
- 【pat-1074】宇宙无敌加法器(高精度)
链接:https://www.patest.cn/contests/pat-b-practise/1074 地球人习惯使用十进制数,并且默认一个数字的每一位都是十进制的.而在PAT星人开挂的世界里,每 ...