SFTP工具类 操作服务器
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工具类 操作服务器的更多相关文章
- SFTP工具类
1.SFTP搭建方法: 地址: http://www.jb51.net/article/101405.htm https://blog.csdn.net/helloloser/article/deta ...
- 基于JSch的Sftp工具类
本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...
- 如何使用Arrays工具类操作数组
介绍 我们要先知道Arrays 是什么. java.util.Arrays 类是 JDK 提供的一个工具类主要用来操作数组,比如数组的复制转换等各种方法,Arrays 的方法都是静态方法可以通过Arr ...
- JDBC--使用beanutils工具类操作JavaBean
1.在JavaEE中,Java类的属性通过getter,setter来定义: 2.可使用BeanUtils工具包来操作Java类的属性: --Beanutils是由Apache公司开发,能够方便对Be ...
- java 时间的原生操作和工具类操作
package com.xc.test.dateoperation; import org.apache.commons.lang3.time.DateFormatUtils; import org. ...
- 使用BeanUtils工具类操作Java bean
1.类的属性: 1).在Java EE中,类的属性通过setter和getter定义:类中的setter(getter)方法去除set(get)后剩余的部分就是类的属性 2).而之前叫的类的属性,即成 ...
- FTP+SFTP工具类封装-springmore让开发更简单
github地址:https://github.com/tangyanbo/springmore FTPUtil 该工具基于org.apache.commons.net.ftp.FTPClient进行 ...
- java SFTP工具类
需要导入jsch-0.1.52.jar import java.io.File; import java.io.FileInputStream; import java.io.FileOutputSt ...
- 利用commons-io.jar包中FileUtils和IOUtils工具类操作流及文件
1.String IOUtils.toString(InputStream input),传入输入流对象,返回字符串,有多重重载,可按需要传参 用例: @Test public void showIn ...
随机推荐
- Problem E
Problem Description 省政府"畅通工程"的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可).现得到城镇道路统计 ...
- pandas数据结构练习题(部分)
更多函数查阅http://pandas.pydata.org/pandas-docs/stable/10min.htmlimport pandas as pd#两种数据结构from pandas im ...
- 蓝桥杯之K好数
如果一个自然数N的K进制表示中任意的相邻的两位都不是相邻的数字,那么我们就说这个数是K好数.求L位K进制数中K好数的数目.例如K = 4,L = 2的时候,所有K好数为11.13.20.22.30.3 ...
- mysql将字符串转化为数字
我的字段为内容为数字,但是类型为字符串,需要使用CASE转换即可 SELECT MAX(CAST(C_id AS UNSIGNED)) INTO id 即查询出来最大的C_id,否则会按照字符串查询最 ...
- 小议webpack下的AOP式无侵入注入
说起来, 面向切面编程(AOP)自从诞生之日起,一直都是计算机科学领域十分热门的话题,但是很奇怪的是,在前端圈子里,探讨AOP的文章似乎并不是多,而且多数拘泥在给出理论,然后实现个片段的定式)难免陷入 ...
- Three ways to throw exception in C#. Which is your preference?
There are three ways to 'throw' a exception in C# C#中有三种抛出异常的方式 Use the throw keyword without an id ...
- java模拟登陆功能
package test; import java.util.Scanner; public class Login { static Scanner sc=new Scanner(System.in ...
- C#移位运算(左移和右移)
C#是用<<(左移) 和 >>(右移) 运算符是用来执行移位运算. 左移 (<<) 将第一个操作数向左移动第二个操作数指定的位数,空出的位置补0. 左移相当于乘. ...
- ASP.NET Core 2.0 MVC「远程」验证
问题 如何 在ASP.NET Core MVC中使用[Remote]属性来实现模型验证 . 解 在 启动时, 为MVC配置中间件和服务. 添加一个模型. 添加一个控制器. 为jQuery添加一个Raz ...
- System.Transactions 事务超时属性
最近遇到一个处理较多数据的大事务,当进行至10分钟左右时,爆出事务超时异常,如果Machine.config中不设置最大超时时间,则默认超时时间为10分钟 MachineSettingsSection ...