[java] SFTP file transfer using Java JSch

Here is my code, which retrieves content of the file, on the remote server and display as output.

package sshexample;

import com.jcraft.jsch.*;
import java.io.*;

public class SSHexample 
{
public static void main(String[] args) 
{
    String user = "user";
    String password = "password";
    String host = "192.168.100.103";
    int port=22;

    String remoteFile="sample.txt";

    try
    {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        System.out.println("Establishing Connection...");
        session.connect();
        System.out.println("Connection established.");
        System.out.println("Creating SFTP Channel.");
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
        System.out.println("SFTP Channel created.");
        InputStream out= null;
        out= sftpChannel.get(remoteFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(out));
        String line;
        while ((line = br.readLine()) != null) 
        {
            System.out.println(line);
        }
        br.close();
        sftpChannel.disconnect();
        session.disconnect();
    }
    catch(JSchException | SftpException | IOException e)
    {
        System.out.println(e);
    }
}
}

Now how to implement this program that the file is copied in the localhost and how to copy a file from localhost to the server.

Here how to make work the transfer of files for any format of files.

This question is related to java ssh sftp file-transfer jsch

The answer is


Usage:

sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");

Implementation


Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to ssh

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058" How to solve "sign_and_send_pubkey: signing failed: agent refused operation"? key_load_public: invalid format ssh connection refused on Raspberry Pi Getting permission denied (public key) on gitlab Verify host key with pysftp Can't connect to Postgresql on port 5432 Checkout Jenkins Pipeline Git SCM with credentials? How to open remote files in sublime text 3 how to setup ssh keys for jenkins to publish via ssh

Examples related to sftp

Upload file to SFTP using PowerShell Google Drive as FTP Server Schedule automatic daily upload with FileZilla FTP/SFTP access to an Amazon S3 Bucket Download files from SFTP with SSH.NET library scp or sftp copy multiple files with single command Single line sftp from terminal Batch file for PuTTY/PSFTP file transfer automation Secure FTP using Windows batch script SFTP file transfer using Java JSch

Examples related to file-transfer

scp copy directory to another server with private key auth SFTP file transfer using Java JSch Viewing root access files/folders of android on windows scp from Linux to Windows Transfer files to/from session I'm logged in with PuTTY how to achieve transfer file between client and server using java socket Comparing HTTP and FTP for transferring files rsync error: failed to set times on "/foo/bar": Operation not permitted

Examples related to jsch

"com.jcraft.jsch.JSchException: Auth fail" with working passwords SFTP file transfer using Java JSch JSchException: Algorithm negotiation fail Can we use JSch for SSH key-based communication? How do I run SSH commands on remote system using Java? Run a command over SSH with JSch com.jcraft.jsch.JSchException: UnknownHostKey scp via java