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;
}

}

版权声明:本文为wangfeng0416原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:http://www.cnblogs.com/wangfeng0416/p/8074849.html