通過JSch - Java實現的SFTP

d2dn 9年前發布 | 2K 次閱讀 Java JSch

 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); } }</pre>

 本文由用戶 d2dn 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!