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. 网络拓展知识 ACL NAT IPv6

    第1章 ACL 访问控制列表 访问控制表(”位代表精确匹配,而“1“位代表不许匹配. 例如路由器EIGRP的配置中: RouterA(config)#router eigrp 100 RouterA( ...

  2. AngularJS学习篇(九)

    AngularJS XMLHttpRequest $http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据. $http.get('someUrl',config).then(s ...

  3. Java多线程Master-Worker模式

    Java多线程Master-Worker模式,多适用于需要大量重复工作的场景中. 例如:使用Master-Worker计算0到100所有数字的立方的和 1.Master接收到100个任务,每个任务需要 ...

  4. 新一代的昆明网络seo优化技巧

    一年一度的双11又即将到来,今天选择在双11这天新注册了一个博客园,第一篇文章,我决定来谈一谈现在的网络SEO. 起首咱们来熟悉下SEO是什么,SEO全名叫Search Engine Optimiza ...

  5. c# 实体类生成工具

    一个简单生成c#实体类的工具 源代码下载

  6. [转]查询sqlserver 正在执行的sql语句的详细信息

    包含用户名,所在数据库,执行的sql语句,执行开始时间,驱动程序,主机名称 SELECT     [Spid] = session_Id, ecid, [Database] = DB_NAME(sp. ...

  7. jquery.base64.js 中文乱码处理

    c# 转码:Convert.ToBase64String(Encoding.UTF8.GetBytes(str)) js 解码:$.base64.atob(this.options.valids, t ...

  8. Ceph编译安装教程

    Ceph官方版本目前支持的纠删码很有限,实验室这块希望能够整合我们自主开发的纠删码BRS(Binary Reed–Solomon encoding),所以需要编译Ceph环境.Ceph官方目前推荐的安 ...

  9. gcc & gdb & make 定义与区别

    GCC 通常所说的GCC是GUN Compiler Collection的简称,除了编译程序之外,它还含其他相关工具,所以它能把易于人类使用的高级语言编写的源代码构建成计算机能够直接执行的二进制代码. ...

  10. 揭秘 HashMap 实现原理(Java 8)

    HashMap 作为一种容器类型,无论你是否了解过其内部的实现原理,它的大名已经频频出现在各种互联网面试中了.从基本的使用角度来说,它很简单,但从其内部的实现来看(尤其是 Java 8 的改进以来), ...