java SFTP工具类
需要导入jsch-0.1.52.jar
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException; /**
* 提供SFTP处理文件服务
*
* @author krm-hehongtao
* @date 2016-02-29
*
*/
public class SFTPUtil {
private JSch jSch = null;
private ChannelSftp sftp = null;// sftp主服务
private Channel channel = null;
private Session session = null; private String hostName = "192.168.0.177";// 远程服务器地址
private int port = 22;// 端口
private String userName = "weblogic";// 用户名
private String password = "weblogic";// 密码 public SFTPUtil(String hostName, int port, String userName, String password) {
this.hostName = hostName;
this.port = port;
this.userName = userName;
this.password = password;
} /**
* 连接登陆远程服务器
*
* @return
*/
public boolean connect() throws Exception {
try {
jSch = new JSch();
session = jSch.getSession(userName, hostName, port);
session.setPassword(password); session.setConfig(this.getSshConfig());
session.connect(); channel = session.openChannel("sftp");
channel.connect(); sftp = (ChannelSftp) channel;
System.out.println("登陆成功:" + sftp.getServerVersion()); } catch (JSchException e) {
System.err.println("SSH方式连接FTP服务器时有JSchException异常!");
System.err.println(e.getMessage());
throw e;
}
return true;
} /**
* 关闭连接
*
* @throws Exception
*/
private void disconnect() throws Exception {
try {
if (sftp.isConnected()) {
sftp.disconnect();
}
if (channel.isConnected()) {
channel.disconnect();
}
if (session.isConnected()) {
session.disconnect();
}
} catch (Exception e) {
throw e;
}
} /**
* 获取服务配置
*
* @return
*/
private Properties getSshConfig() throws Exception {
Properties sshConfig = null;
try {
sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no"); } catch (Exception e) {
throw e;
}
return sshConfig;
} /**
* 下载远程sftp服务器文件
*
* @param remotePath
* @param remoteFilename
* @param localFilename
* @return
*/
public boolean downloadFile(String remotePath, String remoteFilename, String localFilename)
throws SftpException, IOException, Exception {
FileOutputStream output = null;
boolean success = false;
try {
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
} File localFile = new File(localFilename);
// 有文件和下载文件重名
if (localFile.exists()) {
System.err.println("文件: " + localFilename + " 已经存在!");
return success;
}
output = new FileOutputStream(localFile);
sftp.get(remoteFilename, output);
success = true;
System.out.println("成功接收文件,本地路径:" + localFilename);
} catch (SftpException e) {
System.err.println("接收文件时有SftpException异常!");
System.err.println(e.getMessage());
return success;
} catch (IOException e) {
System.err.println("接收文件时有I/O异常!");
System.err.println(e.getMessage());
return success;
} finally {
try {
if (null != output) {
output.close();
}
// 关闭连接
disconnect();
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
}
}
return success;
} /**
* 上传文件至远程sftp服务器
*
* @param remotePath
* @param remoteFilename
* @param localFileName
* @return
*/
public boolean uploadFile(String remotePath, String remoteFilename, String localFileName)
throws SftpException, Exception {
boolean success = false;
FileInputStream fis = null;
try {
// 更改服务器目录
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
}
File localFile = new File(localFileName);
fis = new FileInputStream(localFile);
// 发送文件
sftp.put(fis, remoteFilename);
success = true;
System.out.println("成功发送文件,本地路径:" + localFileName);
} catch (SftpException e) {
System.err.println("发送文件时有SftpException异常!");
e.printStackTrace();
System.err.println(e.getMessage());
throw e;
} catch (Exception e) {
System.err.println("发送文件时有异常!");
System.err.println(e.getMessage());
throw e;
} finally {
try {
if (null != fis) {
fis.close();
}
// 关闭连接
disconnect();
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
}
}
return success;
} /**
* 上传文件至远程sftp服务器
*
* @param remotePath
* @param remoteFilename
* @param input
* @return
*/
public boolean uploadFile(String remotePath, String remoteFilename, InputStream input)
throws SftpException, Exception {
boolean success = false;
try {
// 更改服务器目录
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
} // 发送文件
sftp.put(input, remoteFilename);
success = true;
} catch (SftpException e) {
System.err.println("发送文件时有SftpException异常!");
e.printStackTrace();
System.err.println(e.getMessage());
throw e;
} catch (Exception e) {
System.err.println("发送文件时有异常!");
System.err.println(e.getMessage());
throw e;
} finally {
try {
if (null != input) {
input.close();
}
// 关闭连接
disconnect();
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
} }
return success;
} /**
* 删除远程文件
*
* @param remotePath
* @param remoteFilename
* @return
* @throws Exception
*/
public boolean deleteFile(String remotePath, String remoteFilename) throws Exception {
boolean success = false;
try {
// 更改服务器目录
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
} // 删除文件
sftp.rm(remoteFilename);
System.err.println("删除远程文件" + remoteFilename + "成功!");
success = true;
} catch (SftpException e) {
System.err.println("删除文件时有SftpException异常!");
e.printStackTrace();
System.err.println(e.getMessage());
return success;
} catch (Exception e) {
System.err.println("删除文件时有异常!");
System.err.println(e.getMessage());
return success;
} finally {
// 关闭连接
disconnect();
}
return success;
} /**
* 遍历远程文件
*
* @param remotePath
* @return
* @throws Exception
*/
public List<String> listFiles(String remotePath) throws SftpException {
List<String> ftpFileNameList = new ArrayList<String>();
Vector<LsEntry> sftpFile = sftp.ls(remotePath);
LsEntry isEntity = null;
String fileName = null;
Iterator<LsEntry> sftpFileNames = sftpFile.iterator();
while (sftpFileNames.hasNext()) {
isEntity = (LsEntry) sftpFileNames.next();
fileName = isEntity.getFilename();
System.out.println(fileName);
ftpFileNameList.add(fileName);
}
return ftpFileNameList;
} /**
* 判断路径是否存在
*
* @param remotePath
* @return
* @throws SftpException
*/
public boolean isExist(String remotePath) throws SftpException {
boolean flag = false;
try {
sftp.cd(remotePath);
System.out.println("存在路径:" + remotePath);
flag = true;
} catch (SftpException sException) { } catch (Exception Exception) {
}
return flag;
} public String getHostName() {
return hostName;
} public void setHostName(String hostName) {
this.hostName = hostName;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} 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 static void main(String[] args) {
try {
SFTPUtil sftp = new SFTPUtil("192.168.0.177", 22, "weblogic", "weblogic");
System.out.println(new StringBuffer().append(" 服务器地址: ")
.append(sftp.getHostName()).append(" 端口:").append(sftp.getPort())
.append("用户名:").append(sftp.getUserName()).append("密码:")
.append(sftp.getPassword().toString()));
sftp.connect();
if (sftp.isExist("/home/weblogic/project")) {
sftp.listFiles("/home/weblogic/project");
sftp.downloadFile("/home/weblogic/project", "S123456_20150126.csv",
"D:\\S123456_20150126.csv");
// sftp.uploadFile("\\", "test.txt", "D:\\work\\readMe.txt");
// sftp.deleteFile("\\", "test.txt");
}
} catch (Exception e) {
System.out.println("异常信息:" + e.getMessage());
}
}
}
java SFTP工具类的更多相关文章
- 基于JSch的Sftp工具类
本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...
- SFTP工具类 操作服务器
package com.leadbank.oprPlatform.util;import com.jcraft.jsch.*;import com.jcraft.jsch.ChannelSftp.Ls ...
- SFTP工具类
1.SFTP搭建方法: 地址: http://www.jb51.net/article/101405.htm https://blog.csdn.net/helloloser/article/deta ...
- Java Properties工具类详解
1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...
- Java json工具类,jackson工具类,ObjectMapper工具类
Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
- Java并发工具类 - CountDownLatch
Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...
- MinerUtil.java 爬虫工具类
MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...
- MinerDB.java 数据库工具类
MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...
随机推荐
- 原来不只是fastjson,这个你每天都在用的类库也被爆过反序列化漏洞!
GitHub 15.8k Star 的Java工程师成神之路,不来了解一下吗! GitHub 15.8k Star 的Java工程师成神之路,真的不来了解一下吗! GitHub 15.8k Star ...
- Controller怎么接收Ajax传来的data
var json = { "VendorId": strVendorId, "VendorName": strVendorName, "Remark& ...
- MSF查找提权exp
0x01:介绍 在拿到一个反弹shell后,下一步可以用metaspolit的内置模块Local Exploit SuggesterLocal-exploit-suggester的功能就如它的名字一样 ...
- Yandex企业邮箱申请教程
注册账号 首先你需要有Yandex的账号,这里就不多说了. 注册企业邮箱 注册完账号并登录后打开:https://connect.yandex.com/pdd/ 输入你的域名 来到验证界面,这里建议m ...
- IDEA 2020.1.2 idea 2020.1.3下载 安装 一键破解
IDEA 2020.1.2 idea 2020.1.3下载 安装 破解 本项目只做个人学习研究之用,不得用于商业用途!若资金允许,请点击链接购买正版,谢谢合作!学生凭学生证可免费申请正版授权!创业公司 ...
- 手动造轮子——为Ocelot集成Nacos注册中心
前言 近期在看博客的时候或者在群里看聊天的时候,发现很多都提到了Ocelot网关的问题.我之前也研究过一点,网关本身是一种通用的解决方案,主要的工作就是拦截请求统一处理,比如认证.授权.熔断. ...
- CentOS7 firewalld docker 端口映射问题,firewall开放端口后,还是不能访问,解决方案
# 宿主机ip: 192.168.91.19 docker run -itd --name tomcat -p 8080:8080 tomcat /usr/local/apache-tomcat-9. ...
- 关于SignalR 进行双向多步对话
关于ASP.NET SignalR 解释百度百科是这样说的: ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 ...
- Redis之Redis入门介绍
1.Redis概述 所谓Redis全称为REmote DIctionary Server(远程字典服务器) 是完全开源免费的,用C语言编写的,遵守BSD协议,是一个高性能的(key/value) ...
- 《python开发技术详解》|百度网盘免费下载|Python开发入门篇
<python开发技术详解>|百度网盘免费下载|Python开发入门篇 提取码:2sby 内容简介 Python是目前最流行的动态脚本语言之一.本书共27章,由浅入深.全面系统地介绍了利 ...