Java/J2EEJSchOpen SourceSFTP

Java Program For Uploading File To SFTP Server using JSch SFTP Put

SFTP - Secure File Transfer Protocol

Uploading the file to SFTP server is not easy using Java.net API or Apache‘s Commons.net API. Many of you have faced lots of problems using these API. To upload the file SFTP server you have use the JSCH SFTP API, you can download the API from here. In my previous post i have shown how to download the file from SFTP server. You can read this post here.

Below is the java program for the uploading the file from SFTP server using JSch SFTP Put  –

/**
* Created on July 1, 2010 Copyright(c) https://kodehelp.com All Rights Reserved.
*/
package com.kodehelp.sftp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
 * @author https://kodehelp.com
 *
 */
public class SFTPinJava {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String SFTPHOST = "10.20.30.40";
        int SFTPPORT = 22;
        String SFTPUSER = "username";
        String SFTPPASS = "password";
        String SFTPWORKINGDIR = "/export/home/kodehelp/";

        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);
            File f = new File(FILETOTRANSFER);
            channelSftp.put(new FileInputStream(f), f.getName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

42 Comments

  1. Hi,

    I get following error.

    com.jcraft.jsch.JSchException: Auth cancel
    at com.jcraft.jsch.Session.connect(Session.java:451)
    at com.jcraft.jsch.Session.connect(Session.java:150)

    Please help.

    Thanks,
    Andy

    1. @Andy – Did you added values for below configurations :

      String SFTPHOST = “10.20.30.40”;
      int SFTPPORT = 22;
      String SFTPUSER = “username”;
      String SFTPPASS = “password”;

      Ans also make sure that you have added “NO” at below statement –
      config.put(“StrictHostKeyChecking”, “no”);

    2. This might be failing because your private key was failing authentication; please make sure your are passing the password correctly.

  2. Kushal ·

    Getting below error

    2: No such file

    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2630)

    at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2161)

    at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:315)

    at com.kodehelp.sftp.SFTPinJava.main(SFTPinJava.java:53)

    1. @Kushal – Please make sure you have given correct path for the file which you are trying to upload. Check the below statement in you code File f = new File(FILETOTRANSFER);

      1. Hi Deekay, I have used the below statement to move my file to remote

        String FILETOTRANSFER = “/temp”; // this is the path where i need to push the file from local(C:/Data/sonar/bnyprojects_metrics_new4.csv).

        But i am getting the below exception

        2: No such file
        at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
        at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2340)
        at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:342)
        at com.bnymellon.sonar.Integrator.SFTPinJava.main(SFTPinJava.java:53)

        Could you please help on this:

        Code Below. Please correct if anything here

        public static void main(String[] args) {
        String SFTPHOST = “hostname”;
        int SFTPPORT = 22;
        String SFTPUSER = “user”;
        String SFTPPASS = “password”;
        String SFTPWORKINGDIR = “C:/Data/sonar/bnyprojects_metrics_new4.csv”;
        String FILETOTRANSFER = “/temp”;
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;

        try{
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put(“StrictHostKeyChecking”, “no”);
        session.setConfig(config);
        session.connect();
        channel = session.openChannel(“sftp”);
        channel.connect();
        channelSftp = (ChannelSftp)channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(FILETOTRANSFER);
        // File inputFile = new File(FILETOTRANSFER);

        channelSftp.put(new FileInputStream(f), f.getName());
        }catch(Exception ex){
        ex.printStackTrace();
        }

        }

        }

          1. Hi @Kodehelp:disqus

            Please provide solution, i am also getting same error while trying to upload file.

            /*

            2: File not found

            at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2629)

            */

            My FILETOTRANSFER = ‘/’ //(main directoey)

            FILETOTRANSFER = “D:\server_details.txt” // (it’s local file just for testing)

            Please reply or email on [email protected] if some one get resolved same.

            Thanks

          2. Apologies for typo mistake.

            FILETOTRANSFER = D:\server_details.txt

            SFTPWORKINGDIR = ‘/’

          3. Purnesh ·

            Try this…
            sftp.put(FILETOTRANSFER,SFTPWORKINGDIR,ChannelSftp.OVERWRITE);

      2. Hi Deekay, I have used the below statement to move my file to remote

        String
        FILETOTRANSFER = “/temp”; // this is the path where i need to push the
        file from local(C:/Data/filename.csv).

        But i am getting the below exception

        2: No such file
        at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
        at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2340)
        at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:342)
        at com.bnymellon.sonar.Integrator.SFTPinJava.main(SFTPinJava.java:53)

        Could you please help on this:

        Code Below. Please correct if anything here

        public static void main(String[] args) {
        String SFTPHOST = “hostname”;
        int SFTPPORT = 22;
        String SFTPUSER = “user”;
        String SFTPPASS = “password”;
        String SFTPWORKINGDIR = “C:/Data/myfile.csv”;
        String FILETOTRANSFER = “/temp”;
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;

        try{
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put(“StrictHostKeyChecking”, “no”);
        session.setConfig(config);
        session.connect();
        channel = session.openChannel(“sftp”);
        channel.connect();
        channelSftp = (ChannelSftp)channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(FILETOTRANSFER);
        // File inputFile = new File(FILETOTRANSFER);

        channelSftp.put(new FileInputStream(f), f.getName());
        }catch(Exception ex){
        ex.printStackTrace();
        }

        }

        }

        1. @bkm- you need to correct SFTPWORKINGDIR and FILETOTRANFER values. Please see below corrected values –
          String SFTPWORKINGDIR = “/temp”;
          String FILETOTRANSFER = “C:/Data/myfile.csv”;

  3. Varun Krishna ·

    When I run this code I am getting the following error

    4: The requested operation failed.

    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2833)
    at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2185)
    at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:343)
    at SFTPinJava.main(SFTPinJava.java:56)
    How do I fix this guys? What am I missing?

    Thanks,
    Varun Krishna. P

    1. @varun_krishna:disqus – Please make sure you have correct path in channelSftp.cd(SFTPWORKINGDIR);

      1. Varun Krishna ·

        @Deekay Yeah, initially I had pointed to the wrong directory in the line 38. then did some change to it and it worked fine. Since I am using windows, it supports something like this “folder_name/” and it doesn’t support “/folder_name/”. Thanks. Deekay at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:343) this is the clue right?

        1. @varun_krishna:disqus – That the clue. you are right 🙂 Glad to hear that your issue is fixed.

          1. Deekay I have one more question/doubt about the error message at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2833)
            at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2185)

            Why am I getting these two lines in my error message, when the problem is with the path mentioned in String SFTPWORKINGDIR? Could you please explain it to me?
            I would say that your tutorial is awesome 🙂
            Thanks,
            Varun Krishna. P

  4. karthik ·

    I am able to copy the file content to the server with limitation as below
    1st line on the remote file as
    xyz.abc.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAp8wCyUgYWpmMEau1s/G2yy8Pow8nIoB1JuG8yrlLeAUtGeMq3rODDHyyxzMhExyC7kHeTiCCal31WSF62OkZo8N/gc8Uu3p+jkpdi48M7IiXwD2NrbAQKYeQmiSSP7T1VFxMH5oxGcYzRVV6CEGTFDTrkyFXwg0fekcLrjmHN5lovTH9ptlUjks7zGFJFNMDB6r7LpUbYjx6zpbhs+/nOEn4hdlCotWjbfIM+uqRVvdfz4eGISgdmPyYYQSlwJ8W58eaAfTbEyluN3e2JNoaJ9LxC391Q/o0EA4Yx3pycsFeRIRjmJyoYOFfACRzw/zS/Bv/79ZlcRA/9tIdyl05vQ==

    Can any one help me, How to avoid this?

    Thanks in advance

  5. Nitesh Komalwar ·

    line no 58:
    channelSftp.put(new FileInputStream(f), f.getName());

    this will result in creating new file input stream, and will keep the file in use until the program is not terminated.
    instead you must use

    FileInputStream fis = new FileInputStream(f);
    channelSftp.put(fis, f.getName());
    fis.close();

    so that the file input stream is properly closed.

  6. I’m posting a simple text file to an SFTP server, with size about 80 KB. But after every sucessfull post, the result file alway have the file size around 30 KB.
    I tried with with many differet files sizes, and only the files above 30 KB gets truncated and limit to 30 KB. The files below 30 KB gets uploaded properly with all data intact.
    Thanks in advance!!

    1. I’m facing the same error, can’t upload files > 20K, if the file is >20K then on remote folder the file is only 16K

      1. @Yash and @Hao – Can anyone of you share your code to upload file > 20kb to sftp ?Please remove your sftp credentials from the code before sharing it with me.

        1. nothing special in the code

          public static void putFile(String username, String host, String password, String remotefile, String localfile){

          JSch jsch = new JSch();

          Session session = null;

          Channel channel = null;

          ChannelSftp channelSftp = null;

          try {

          session = jsch.getSession(username, host, 22);

          java.util.Properties config = new java.util.Properties();

          config.put(“StrictHostKeyChecking”, “no”);

          session.setConfig(config);

          session.setPassword(password);

          session.setServerAliveInterval(0);
          session.setServerAliveCountMax(3);

          session.connect();

          channel = session.openChannel(“sftp”);

          channel.connect();

          channelSftp = (ChannelSftp)channel;

          channelSftp.cd(“/TempFolder/”);

          File f = new File(localfile);

          channelSftp.put(f.getAbsolutePath(), f.getName(), ChannelSftp.OVERWRITE);

          channel.disconnect();

          session.disconnect();

    2. Can you share your code to upload file > 20kb to sftp ? Please remove your sftp credentials from the code before sharing it with me.

  7. Mustufa ·

    Hi Team,
    I am trying to connect to sftp server using password authentication.
    I have used the same above mentioned example, but I got error UnknownHostKey error. So I have manually tried to connect to sftp server and created entry on my Linux server. Now I am setting UnknowHostKey path in my code and removed StrictHostKeyChecking from code, but unfortunately I am not getting jsch session.

    Could you please let me know that can I use both UnknowHostKey and StrictHostKeyChecking together in code?
    Also I have spring project and i have not used Spring Outbound Adapter, Do I need to use this or the basic Jsch code will work in my spring project?

    If you need my code then I can paste it here for more clarification.

    Please advice me as I got stuck here.

    Thanks,
    Mustufa

    1. @Mustafa – You can use HostKey Path and StrictHostKeyChecking together. Could you please share your code at admin[at]kodehelp.com

  8. Sanghmitra sanghu ·

    i am able to upload only empty files. files with any content inside is not getting uploaded and getting these below exections:

    4: Failure

    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)

    at com.jcraft.jsch.ChannelSftp.checkStatus(ChannelSftp.java:2459)

    at com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:677)

    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:540)

    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:492)

    at com.sanghu.service.jschtest.upload(jschtest.java:68)

    at com.sanghu.service.jschtest.main(jschtest.java:97)

  9. Mansuri Naeem ·

    Hi, I am getting Permission denied error

    3: Permission denied
    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2873)
    at com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:594)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:540)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:492)
    at support.Testing.main(Testing.java:41)

    1. @mansurinaeem:disqus – Please check if the remote directory exists or the user has write permissions on the directory.

  10. sharon ·

    i am trying to upload file to windows server which is causing below error… com.jcraft.jsch.JSchException: Session.connect: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive)…what i hav to do?

  11. Justin Raj S ·

    Hi Deepak,
    Thanks for this nice post, i have tried above and getting “com.jcraft.jsch.JSchException: Auth fail” Exception while upload files to SFTP Path. Can you please Provide any suggestion/solution?
    Thanks in advance.
    Note:
    Username contains special character
    /*To upload each file from localpath*/
    public static int directUpload (String fileName,int status) {
    String SFTPHOST = “hostname”;
    int SFTPPORT = “port”;
    String SFTPUSER = “abc-env”;
    String SFTPPASS = “U78A0hTfhjduthkl”;
    //String SFTPWORKINGDIR = “/wso2/Process/VB/EmailImages”;
    String SFTPWORKINGDIR = “/home/test-dev/EmailImages”;
    sftp_path=”https://”+SFTPHOST+SFTPWORKINGDIR+”/”;
    System.out.println(“====SFTP Upload Path:====”+sftp_path);
    File f=null;
    com.jcraft.jsch.Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println(“preparing the host information for sftp.”);

    try {
    JSch jsch = new JSch();
    session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
    session.setPassword(SFTPPASS);
    java.util.Properties config = new java.util.Properties();
    config.put(“StrictHostKeyChecking”, “no”);
    config.put(“PreferredAuthentications”, “password”);
    session.setConfig(config);
    session.connect();
    System.out.println(“Host connected.”);
    channel = session.openChannel(“sftp”);
    channel.connect();
    System.out.println(“sftp channel opened and connected.”);
    channelSftp = (ChannelSftp) channel;
    channelSftp.cd(SFTPWORKINGDIR);
    f = new File(fileName);
    channelSftp.put(new FileInputStream(f), f.getName());
    status=1;
    System.out.println(“File transfered successfully to host.”);
    } catch (Exception ex) {
    ex.printStackTrace();
    status=0;
    System.out.println(“Exception found while tranfer the response.”);

    } finally {
    channelSftp.exit();
    System.out.println(“sftp Channel exited.”);
    channel.disconnect();
    System.out.println(“Channel disconnected.”);
    session.disconnect();
    System.out.println(“Host Session disconnected.”);

    }
    return status;
    }

  12. Justin Raj S ·

    Hi Deepak,
    Thank you so much for this nice post. I have followed the same way u did. But got below exception. Could anyone please help me out to find the solution???
    Thanks in advance.
    “com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(Session.java:519)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at com.qrs.in.EmailAttachmentReceiver.directUpload(EmailAttachmentReceiver.java:139)
    at com.qrs.in.EmailAttachmentReceiver.send(EmailAttachmentReceiver.java:111)etc”
    Source Code:
    /*To upload each file from localpath*/
    public static int directUpload (String fileName,int status) {
    String SFTPHOST = “hostname”;
    int SFTPPORT = port;
    String SFTPUSER = “abc-test”;
    String SFTPPASS = “U46A0hjklikjhgstw”;
    String SFTPWORKINGDIR = “/home/qrs-dev/EmailImages”;
    File f=null;
    com.jcraft.jsch.Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println(“preparing the host information for sftp.”);

    try {
    JSch jsch = new JSch();
    session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
    session.setPassword(SFTPPASS);
    java.util.Properties config = new java.util.Properties();
    config.put(“StrictHostKeyChecking”, “no”);
    config.put(“PreferredAuthentications”, “publickey”);
    session.setConfig(config);
    session.connect();
    System.out.println(“Host connected.”);
    channel = session.openChannel(“sftp”);
    channel.connect();
    System.out.println(“sftp channel opened and connected.”);
    channelSftp = (ChannelSftp) channel;
    channelSftp.cd(SFTPWORKINGDIR);
    f = new File(fileName);
    channelSftp.put(new FileInputStream(f), f.getName());
    status=1;
    System.out.println(“File transfered successfully to host.”);
    } catch (Exception ex) {
    ex.printStackTrace();
    status=0;
    System.out.println(“Exception found while tranfer the response.”);

    } finally {
    channelSftp.exit();
    System.out.println(“sftp Channel exited.”);
    channel.disconnect();
    System.out.println(“Channel disconnected.”);
    session.disconnect();
    System.out.println(“Host Session disconnected.”);

    }
    return status;
    }

Leave a Comment

Your email address will not be published. Required fields are marked *