package com.leadbank.oprPlatform.util;

import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.leadbank.oprPlatform.module.SSHInfo;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.sftp.IdentityInfo;
import org.apache.commons.vfs2.provider.sftp.SftpClientFactory;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

/**
* SFTP工具类
*/
public class SFTPUtil {

private int interval = 1000;
private ChannelSftp channel;
private Session session;
/** 规避多线程并发 */
private static ThreadLocal<SFTPUtil> sftpLocal = new ThreadLocal<SFTPUtil>();

public SFTPUtil() {
channel = null;
}

public static void main(String[] args) {
SFTPUtil s = new SFTPUtil();
try {
SSHInfo info = new SSHInfo("xxx",xxx,"xxx","c:/Users/user/.ssh/id_rsa",null);
s.connect(info);
//s.downloadFileAfterCheck("/usr/local/leadsys/tomcat-7.0.50/logs/localhost.2017-11-15.log","d://1.log");
s.uploadFile("d:/test.sh","/usr/local/leadsys/test.sh");
s.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* SFTP连接建立
*
* @return
* @throws JSchException
*/
public boolean connect(SSHInfo info) throws JSchException {
//If the client is already connected, disconnect
if (channel != null) {
disconnect();
}
FileSystemOptions fso = new FileSystemOptions();

try {
if(null != info.getPassPhrase() && !"".equals(info.getPassPhrase())){//判断密码为空
//密码登录
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fso, "no");
session = SftpClientFactory.createConnection(info.getHost(), info.getPort(), info.getUser().toCharArray(), info.getPassPhrase().toCharArray(), fso);
}else{
//密钥登录
SftpFileSystemConfigBuilder.getInstance().setIdentityInfo(fso, new IdentityInfo(new File(info.getKey())));
//SftpFileSystemConfigBuilder.getInstance().setUserInfo(fso,new MyUserInfo(info.getKey()));
SftpFileSystemConfigBuilder.getInstance().setTimeout(fso, new Integer(interval));//设置超时
session = SftpClientFactory.createConnection(info.getHost(), info.getPort(), info.getUser().toCharArray(), null, fso);
}

channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
} catch (FileSystemException e) {
e.printStackTrace();
return false;
}
return channel.isConnected();
}

/**
* SFTP断开连接
*/
public void disconnect() {
if (channel != null) {
channel.exit();
}
if (session != null) {
session.disconnect();
}
channel = null;
}

/**
* 是否已连接
*
* @return
*/
private boolean isConnected() {
return null != channel && channel.isConnected();
}

/**
* 显示目录下所有文件名
* @param remoteDir
* @return
* @throws Exception
*/
public Vector<String> listFileInDir(String remoteDir) throws Exception {
try {
Vector<LsEntry> rs = channel.ls(remoteDir);
Vector<String> result = new Vector<String>();
for (int i = 0; i < rs.size(); i++) {
if (!isARemoteDirectory(rs.get(i).getFilename())) {
result.add(rs.get(i).getFilename());
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
System.err.println(remoteDir);
throw new Exception(e);
}
}

/**
* 获取目录中的子文件夹
* @param remoteDir
* @return
* @throws Exception
*/
public Vector<String> listSubDirInDir(String remoteDir) throws Exception {
Vector<LsEntry> rs = channel.ls(remoteDir);
Vector<String> result = new Vector<String>();
for (int i = 0; i < rs.size(); i++) {
if (isARemoteDirectory(rs.get(i).getFilename())) {
result.add(rs.get(i).getFilename());
}
}
return result;
}

/**
* 创建目录
* @param dirName
* @return
*/
protected boolean createDirectory(String dirName) {
try {
channel.mkdir(dirName);
} catch (Exception e) {
return false;
}
return true;
}

/**
* 创建多层目录
* @param path
* @return
* @throws SftpException
*/
public boolean createDirs(String path) throws SftpException {
try {
channel.cd("/");
System.out.println(getWorkingDirectory());
String[] folders = path.split( "/" );
for ( String folder : folders ) {
if ( folder.length() > 0 ) {
try {
channel.cd( folder );
String workingDirectory = getWorkingDirectory();
System.out.println(workingDirectory);
}
catch ( SftpException e ) {
channel.mkdir( folder );
channel.cd( folder );
String workingDirectory = getWorkingDirectory();
System.out.println(workingDirectory);
}
}
}
return true;
} catch (SftpException e) {
e.printStackTrace();
return false;
}
}

/**
* 下载远程文件到本地指定文件,包含检查
* @param remotePath
* @param localPath
* @return
* @throws IOException
*/
protected boolean downloadFileAfterCheck(String remotePath, String localPath) throws IOException {
FileOutputStream outputSrr = null;
try {
File file = new File(localPath);
if (!file.exists()) {
outputSrr = new FileOutputStream(localPath);
channel.get(remotePath, outputSrr);
}
} catch (SftpException e) {
try {
System.err.println(remotePath + " not found in " + channel.pwd());
} catch (SftpException e1) {
e1.printStackTrace();
}
e.printStackTrace();
return false;
} finally {
if (outputSrr != null) {
outputSrr.close();
}
}
return true;
}

/**
* 下载远程文件到本地文件
* @param remotePath
* @param localPath
* @return
* @throws IOException
*/
protected boolean downloadFile(String remotePath, String localPath) throws IOException {
FileOutputStream outputSrr = new FileOutputStream(localPath);
try {
channel.get(remotePath, outputSrr);
} catch (SftpException e) {
try {
System.err.println(remotePath + " not found in " + channel.pwd());
} catch (SftpException e1) {
e1.printStackTrace();
}
e.printStackTrace();
return false;
} finally {
if (outputSrr != null) {
outputSrr.close();
}
}
return true;
}

/**
* 上传本地文件至远程文件
* @param localPath
* @param remotePath
* @return
* @throws IOException
*/
public boolean uploadFile(String localPath, String remotePath) throws IOException {
FileInputStream inputSrr = new FileInputStream(localPath);
try {
channel.put(inputSrr, remotePath);
} catch (SftpException e) {
e.printStackTrace();
return false;
} finally {
if (inputSrr != null) {
inputSrr.close();
}
}
return true;
}

/**
* 切换当前目录
* @param remotePath
* @return
* @throws Exception
*/
public boolean changeDir(String remotePath) throws Exception {
try {
channel.cd(remotePath);
} catch (SftpException e) {
return false;
}
return true;
}

/**
* 是否为目录
* @param path
* @return
*/
public boolean isARemoteDirectory(String path) {
try {
return channel.stat(path).isDir();
} catch (SftpException e) {
//e.printStackTrace();
}
return false;
}

/**
* 获得当前执行路径
* @return
*/
public String getWorkingDirectory() {
try {
return channel.pwd();
} catch (SftpException e) {
e.printStackTrace();
}
return null;
}

}

SFTP工具类 操作服务器的更多相关文章

  1. SFTP工具类

    1.SFTP搭建方法: 地址: http://www.jb51.net/article/101405.htm https://blog.csdn.net/helloloser/article/deta ...

  2. 基于JSch的Sftp工具类

    本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...

  3. 如何使用Arrays工具类操作数组

    介绍 我们要先知道Arrays 是什么. java.util.Arrays 类是 JDK 提供的一个工具类主要用来操作数组,比如数组的复制转换等各种方法,Arrays 的方法都是静态方法可以通过Arr ...

  4. JDBC--使用beanutils工具类操作JavaBean

    1.在JavaEE中,Java类的属性通过getter,setter来定义: 2.可使用BeanUtils工具包来操作Java类的属性: --Beanutils是由Apache公司开发,能够方便对Be ...

  5. java 时间的原生操作和工具类操作

    package com.xc.test.dateoperation; import org.apache.commons.lang3.time.DateFormatUtils; import org. ...

  6. 使用BeanUtils工具类操作Java bean

    1.类的属性: 1).在Java EE中,类的属性通过setter和getter定义:类中的setter(getter)方法去除set(get)后剩余的部分就是类的属性 2).而之前叫的类的属性,即成 ...

  7. FTP+SFTP工具类封装-springmore让开发更简单

    github地址:https://github.com/tangyanbo/springmore FTPUtil 该工具基于org.apache.commons.net.ftp.FTPClient进行 ...

  8. java SFTP工具类

    需要导入jsch-0.1.52.jar import java.io.File; import java.io.FileInputStream; import java.io.FileOutputSt ...

  9. 利用commons-io.jar包中FileUtils和IOUtils工具类操作流及文件

    1.String IOUtils.toString(InputStream input),传入输入流对象,返回字符串,有多重重载,可按需要传参 用例: @Test public void showIn ...

随机推荐

  1. ASP.NET Core的身份认证框架IdentityServer4(4)- 支持的规范

    IdentityServer实现以下规范: OpenID Connect OpenID Connect Core 1.0 (spec) OpenID Connect Discovery 1.0 (sp ...

  2. Day1作业要求

    Day1作业 作业需求 博客 模拟登录 三级菜单 博客地址 杨振伟Day1博客地址 模拟登录 1.程序说明 实现功能如下 用户输入密码,密码验证后登录成功 用户登录成功后提示登录信息 用户输入3次错误 ...

  3. Problem F: 多少个最大值?

    Description 输入若干个int类型的整数,求它们的最大值及其个数. Input 输入 若干个int类型的整数,至文件尾为止. Output 输出只有一行:There are # maximu ...

  4. Python爬虫入门:Urllib库的高级使用

    1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览 ...

  5. 谈一次java web系统的重构思路

    ——略谈Java web软件如何提供二次开发接口 接手公司的一个Java web软件产品,该软件采用传统的dwr框架.dwr框架相当于一个中间层,使得javascript能够识别Java类对象,进而能 ...

  6. Spring Security Ajax 被拦截

    背景是项目中使用Spring Security 进行安全控制 再使用Ajax的时候会报 403(ajax get  方式是没问题的 post 的时候会报) Spring Security 原本是 防止 ...

  7. 【OpenCV】通过ROI区域以及掩码实现图像叠加

    在图像处理领域,我们常常需要设置感兴趣区域(ROI,region of interest),来专注或者简化我们的工作过程 .也就是从图像中选择的一个图像区域,这个区域是我们图像分析所关注的重点.我们圈 ...

  8. 微软Connect(); 2017大会梳理:Azure、数据、AI开发工具

    在今天召开的 Connect(); 2017 开发者大会上,微软宣布了 Azure.数据.AI 开发工具的内容.这是第一天的 Connect(); 2017 的主题演讲. 在开场视频中霍金又来了.你记 ...

  9. 走进Spark生态圈:环境的安装与配置

    什么是Spark? Apache Spark 是一种大规模数据处理的快速通用引擎,使用基于内存的处理方式,较与MapReduce而言,解决了其shuffle多次IO操作带来的效率低问题,从而达到快速的 ...

  10. 关于 innodb_stats_on_metadata 的设置问题

    [问题背景] 线上使用osc进行表修改的时候出现SQL执行过长被kill的问题