JSchを使ってSFTPでPUTするサンプル

  1. import java.util.Hashtable;
  2. import com.jcraft.jsch.ChannelSftp;
  3. import com.jcraft.jsch.JSch;
  4. import com.jcraft.jsch.JSchException;
  5. import com.jcraft.jsch.Session;
  6. import com.jcraft.jsch.SftpException;
  7. /**
  8. * SFTP転送クラス
  9. * 鍵認証方式、パスワード方式のどちらでも接続可能。
  10. * 接続にはJSch(0.1.51)を使用。
  11. *
  12. */
  13. public class SftpUtil {
  14.     private String hostName = "";
  15.     private String userId = "";
  16.     private String password = "";
  17.     private String knownhosts = "";
  18.     private String privateKey = "";
  19.     private final int port = 22;
  20.     /**
  21.      * コンストラクタ
  22.      *
  23.      * @param _hostName 接続先のURL
  24.      * @param _userId ユーザーID
  25.      * @param _password パスワード ※秘密鍵を指定している場合は省略可能
  26.      * @param _knownhosts known_hosts(公開鍵)のフルパス ※秘密鍵を指定している場合は省略可能
  27.      *        windows7のTeraTermの場合はC:\Users\(ユーザー名)\AppData\Local\VirtualStore\Program Files\teraterm\ssh_known_hosts
  28.      * @param _priveteKey 秘密鍵のフルパス
  29.      */
  30.     public SftpUtil(String _hostName, String _userId, String _password, String _knownhosts, String _priveteKey) {
  31.         hostName = _hostName;
  32.         userId = _userId;
  33.         password = _password;
  34.         knownhosts = _knownhosts;
  35.         privateKey = _priveteKey;
  36.     }
  37.     /**
  38.      * リモートホストへ接続
  39.      *
  40.      * @return
  41.      * @throws JSchException
  42.      */
  43.     private Session connect() throws JSchException {
  44.         JSch jsch = new JSch();
  45.         Session session = null;
  46.         try {
  47.             if (privateKey != null && privateKey.length() > 0) {
  48.                 // 秘密鍵の設定
  49.                 jsch.addIdentity(privateKey);
  50.             }
  51.             if (knownhosts != null && knownhosts.length() > 0) {
  52.                 // known_hosts(公開鍵)の設定
  53.                 jsch.setKnownHosts(knownhosts);
  54.             }
  55.             else {
  56.                 Hashtable config = new Hashtable();
  57.                 // 公開鍵の指定が無い場合は、厳密なチェックを行わないように設定しておく必要がある
  58.                 config.put("StrictHostKeyChecking", "no");
  59.                 JSch.setConfig(config);
  60.             }
  61.             session = jsch.getSession(userId, hostName, port);
  62.             if (privateKey == null || privateKey.length() == 0) {
  63.                 // 秘密鍵が指定されていない場合はパスワードを設定
  64.                 session.setPassword(password);
  65.             }
  66.             session.connect();
  67.             return session;
  68.         }
  69.         catch (JSchException ex) {
  70.             throw ex;
  71.         }
  72.     }
  73.     /**
  74.      * SFTPでローカルファイルをリモートへ転送
  75.      *
  76.      * @param from 転送したいローカルファイルのフルパス
  77.      * @param dist 転送先のパス
  78.      * @throws JSchException
  79.      * @throws SftpException
  80.      */
  81.     public void put(String from, String dist) throws JSchException, SftpException {
  82.         Session session = null;
  83.         ChannelSftp channel = null;
  84.         try {
  85.             // リモートホストへ接続
  86.             session = connect();
  87.             // SFTP開始
  88.             channel = (ChannelSftp) session.openChannel("sftp");
  89.             channel.connect();
  90.         }
  91.         catch (JSchException ex) {
  92.             throw ex;
  93.         }
  94.         try {
  95.             // ファイル名を取得
  96.             String[] tmp = from.split("/");
  97.             String fileName = tmp[tmp.length - 1];
  98.             // 転送先のパスへ移動
  99.             channel.cd(dist);
  100.             // ファイル転送
  101.             channel.put(from, fileName);
  102.         }
  103.         catch (SftpException ex) {
  104.             throw ex;
  105.         }
  106.         finally {
  107.             if (channel != null) {
  108.                 channel.disconnect();
  109.             }
  110.             if (session != null) {
  111.                 session.disconnect();
  112.             }
  113.         }
  114.     }
  115. }
【使用例】
// 鍵認証方式で接続する場合
SftpUtil util = new SftpUtil("接続先URL", "ユーザID", null, null, "鍵ファイルのフルパス");

// パスワード方式で接続する場合 ※パスワード方式は未検証。たぶん動くはずです(^^;
SftpUtil util = new SftpUtil("接続先URL", "ユーザID", "パスワード", null, null);

try {
    util.put("C:/Temp/test.txt", "/home/testUser/");
}
catch (JSchException | SftpException e) {
   e.printStackTrace();
}

戻る