java sftp工具类_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 sftpLocal = new ThreadLocal();

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 listFileInDir(String remoteDir) throws Exception {

try {

Vector rs = channel.ls(remoteDir);

Vector result = new Vector();

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 listSubDirInDir(String remoteDir) throws Exception {

Vector rs = channel.ls(remoteDir);

Vector result = new Vector();

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值