LoginSignup
7
7

More than 5 years have passed since last update.

JSchを使って、sftpでファイルを送信しようとしたらcom.jcraft.jsch.JSchException: UnknownHostKey

Last updated at Posted at 2015-10-07

jsch.setKnownHosts("path_to_known_hosts")で、フィンガープリントを教えてあげると接続してくれる

public static void main(String args) {
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;

        try(InputStream input = fileService.loadFile("filePath") {
            JSch jsch = new JSch();

            jsch.addIdentity("key_to_prv_key_path"); // 秘密鍵指定
            jsch.setKnownHosts("~/.ssh/known_hosts"); // ←これ
            session = jsch.getSession(user, hostname, port);

            // このやりかたはなぜかうまくいかなかった
    //                Properties config = new Properties();
    //                config.setProperty("StringHostKeyChecking", "no");
    //                session.setConfig(config);

            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();

            channelSftp = (ChannelSftp) channel;
            channelSftp.put(input, "fileName");
        } finally {
            channelSftp.exit();
            channel.disconnect();
            session.disconnect();
        }
}

参考

7
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7