どうしても、Javaサーブレットからリモートにファイルを転送しなくてはいけなくなりました。

色々方法はあるんですが、大掛かりというか、面倒なのは嫌です。

Antタスクで、サーバにデプロイを自動化する際に、さんざんお世話になっているJSchを使用すれば、結構楽に実現できます。

下記にはありませんが、ls や get もフツーに出来ます。

JSchの難点は参考サイトにもありますが、JavaDocさえ無い不親切さですが、

一度ユーティリティクラスを書いておけば、結構使えるのでは無いかと。

import java.util.Vector;
import java.io.IOException;
import com.jcraft.jsch.*;

public class Sftp {

    private static String hostname_   = null;
    private static String userid_     = null;
    private static String password_   = null;
    private static String knownhosts_ = null;
    private static String privatekey_ = null;

    public Sftp( String hostname
                , String userid
                , String password
                , String knownhosts
                , String privatekey ) 
    {
        hostname_   = hostname;
        userid_     = userid;
        password_   = password;
        knownhosts_ = knownhosts;
        privatekey_ = privatekey;
    }

    public void doPut(String from, String dist) 
        throws JSchException, SftpException, IOException 
    {

        JSch jsch=new JSch();
        Session session     = null;
        ChannelSftp channel = null;
        try {
            if (privatekey_ != null && !"".equals(privatekey_)) {
                jsch.addIdentity(privatekey_);
            }
            jsch.setKnownHosts(knownhosts_);
            session = jsch.getSession(userid_, hostname_, 22);
            if (privatekey_ == null || "".equals(privatekey_)) {
                session.setPassword(password_);
            }
            session.connect();
            channel = (ChannelSftp)session.openChannel("sftp");
            channel.connect();
        } catch (JSchException ex ) {
            //
        }

        try {
            channel.put(from, dist);
            channel.disconnect();
            session.disconnect();
        } catch (SftpException ex ) {
            //
        }
    }
}

参考サイト

Java で ssh や scp を呼び出す(7) – JSch で sftp 編 – Mi manca qualche giovedi`?

Gallery lumber-mill – JSch – SSLライブラリ