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. 2015-2016 ACM-ICPC, NEERC, Southern Subregional Contest A Email Aliases(模拟STL vector+map)

    Email AliasesCrawling in process... Crawling failed Time Limit:2000MS     Memory Limit:524288KB     ...

  2. Codeforces Round #378 (Div. 2)-C. Epidemic in Monstropolis

    C. Epidemic in Monstropolis time limit per test 1 second memory limit per test 256 megabytes input s ...

  3. ssh连接虚拟机失败解决办法

    首先,你需要知道本机IP跟虚拟机IP,然后让两者互相ping一下,看能否ping通 让主机ping虚拟机 :ping (虚拟机ip) 出现如下: 表示主机可以ping通虚拟机 然后让虚拟机ping主机 ...

  4. css给div添加阴影效果

    直接上代码: <style type="text/css">.mydiv{   width:250px; height:auto; border:#909090 1px ...

  5. javaSE基础

     变量 1.变量就是数据存储空间的表示. 2.标识符命名规则:变量名=首字母+其余部分 ①首字母:字母.下划线.“$”符号(开头) ②其余部分:数字.字母.下划线“$” ③应避开关键字:int int ...

  6. C语言实现二叉树的基本操作

    二叉树是一种非常重要的数据结构.本文总结了二叉树的常见操作:二叉树的构建,查找,删除,二叉树的遍历(包括前序遍历.中序遍历.后序遍历.层次遍历),二叉搜索树的构造等. 1. 二叉树的构建 二叉树的基本 ...

  7. Scrum Meeting Alpha - 2

    Scrum Meeting Alpha - 2 NewTeam 2017/10/25 地点:新主楼F座二楼 任务反馈 团队成员 完成任务 计划任务 安万贺 完成了大部分api的测试https://gi ...

  8. Windows常用shell命令大全

    Windows常用shell命令大全 基于鼠标操作的后果就是OS界面外观发生改变, 就得多花学习成本.更主要的是基于界面引导Path与命令行直达速度是难以比拟的.另外Geek很大一部分是键盘控,而非鼠 ...

  9. vmware中Ubuntu不能全屏展示的问题

    依次打开system settings---------------->Displays----------------->resoluiton调整分辨率,然后右下角点击apply,然后k ...

  10. php多个文件上传

    表单如下 <form class="form-horizontal" action="{:U('System/addAdvert')}" method=& ...