通过JSch - Java实现的SFTP

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

 JSch是Java Secure Channel的缩写。JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。

  本文只介绍如何使用JSch实现的SFTP功能。

  SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式。SFTP是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输 方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。(来自百度的解释) 

  要使用JSch,需要下载它的jar包,请从官网下载它:http://www.jcraft.com/jsch/

import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Vector;
 
import org.apache.commons.httpclient.auth.AuthenticationException;
 
import com.ebao.jewel.gs.integration.pub.CommonLog.exception.ExceptionUtil;
import com.ebao.jewel.gs.integration.pub.CommonLog.utils.JewelIntLogUtils;
import com.ebao.jewel.gs.integration.pub.commons.InterfaceUtil;
import com.ebao.jewel.gs.integration.pub.connection.IConnection;
import com.ebao.jewel.gs.integration.pub.constants.InterfaceConstants;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
 
public class JewelSftpClient implements IConnection {
 
  private Session sshSession = null;
 
  private ChannelSftp channelSftp = null;
 
  private int connectTimes = 0;
 
  public boolean connect(String host, int port, String username, String pwd)
 
  throws Exception {
    if (sshSession == null || !sshSession.isConnected()) {
 
      JSch jsch = new JSch();
 
      try {
        sshSession = jsch.getSession(username, host, port);
      } catch (JSchException je) {
        // throw new Connection
        throw je;
      }
    }
    if (!sshSession.isConnected()) {
      InterfaceUtil.batchLog("[TEST] sshSession.connect()");
      sshSession.setPassword(pwd);
 
      Properties sshConfig = new Properties();
      sshConfig.put("StrictHostKeyChecking", "no");
      sshSession.setConfig(sshConfig);
      try {
        sshSession.connect();
      } catch (JSchException ex) {
 
        if (ex.getMessage().indexOf("Session.connect") != -1) {
          throw new UnknownHostException(ExceptionUtil.getExceptionMsg(ex));
        } else {
          throw new AuthenticationException(ExceptionUtil.getExceptionMsg(ex));
        }
      }
    }
    InterfaceUtil.batchLog("[TEST] sshSession has connected.");
    try {
      if (channelSftp == null || !channelSftp.isConnected()) {
        InterfaceUtil.batchLog("[TEST] channelSftp.connect()");
        channelSftp = (ChannelSftp) sshSession.openChannel("sftp");
        channelSftp.connect();
      }
 
      InterfaceUtil.batchLog("[TEST] channelSftp has been established.");
      return true;
    } catch (JSchException je) {
      if (connectTimes++ < InterfaceConstants.MAX_CONNECT_TIMES) {
        String seq = connectTimes == 1 ? "1st" : connectTimes == 2
            ? "2nd"
            : connectTimes == 3 ? "3rd" : connectTimes + "st";
        InterfaceUtil.batchLog("[TEST]" + seq
            + " connection failed. Disconnected "
            + (disconnect() == true ? "succeeded" : "failed"));
        long sleepTime = InterfaceUtil.getConnectSleepTime() * 1000L;
        Thread.sleep(sleepTime);
        InterfaceUtil.batchLog("[TEST]" + sleepTime + " ms passed. Try "
            + (int) (connectTimes + 1) + " connection.");
        if (connectTimes == 4) {
          InterfaceUtil
              .batchLog("[TEST] !!!!!!!!!!!connection goes wrong!!!!!!!!!!!!!!!!");
        }
        return connect(host, port, username, pwd);
      } else {
        InterfaceUtil.batchLog("[TEST] connect excceeded 10 times.");
        throw je;
      }
    }
  }
 
  public boolean disconnect() throws Exception {
    try {
      if (channelSftp != null && channelSftp.isConnected()) {
 
        channelSftp.disconnect();
        InterfaceUtil.batchLog("[TEST] channelSftp has cloesd.");
      }
      if (sshSession != null && sshSession.isConnected()) {
 
        sshSession.disconnect();
        InterfaceUtil.batchLog("[TEST] sshSession has cloesd.");
      }
      return true;
    } catch (Exception e) {
      return false;
 
    }
 
  }
 
  public void upload(String src, String dst) throws Exception {
    channelSftp.put(src, dst);
  }
 
  public void download(String src, String dst) throws Exception {
    channelSftp.get(src, dst);
 
  }
 
  @SuppressWarnings("unchecked")
  public Vector<Object> listFiles(String directory) throws Exception {
    try {
      channelSftp.cd(directory);
    } catch (Exception e) {
      throw new FileNotFoundException("No such file or directory.src:"
          + directory);
    }
    Vector<Object> files = channelSftp.lsnames(directory);
    return files;
 
  }
 
  public boolean moveFile(String src, String dst) throws Exception {
    try {
      channelSftp.rename(src, dst);
      return true;
    } catch (Exception e) {
      JewelIntLogUtils.batchLog("[TEST] Move the file from " + src + " to "
          + dst + " fail", e);
      throw e;
    }
  }
 
  public boolean isConnected() {
    return channelSftp != null && channelSftp.isConnected();
  }
 
  @Override
  public void download(String src, OutputStream out) throws Exception {
    channelSftp.get(src, out);
  }
}

标签: 安全 服务器 网络 网络安全 网络安全性

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Java判断图片格式的代码

下一篇:JFreeChart生成柱形图代码