Disqus for hsalearn

JSCH - Java Secure Channel.

Introduction:

JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. To read more about JSch please follow the link http://www.jcraft.com/jsch/

Please note JSch is not an FTP client. JSch is an SSH client (with an included SFTP implementation).

The SSH protocol is a protocol to allow secure connections to a server, for shell access, file transfer or port forwarding. For this, the server must have an SSH server (usually on port 22, but that can vary). SFTP is a binary file transfer protocol which is usually tunneled over SSH, and not related to FTP (other than by name).

If you want to use JSch to download/upload files, you need to install and activate an SSH/SFTP server on your computer (respective the computer you want to access).

For FTP, you have to use other Java libraries (Apache Commons FTPClient seems to be famous, from the questions here).

By the way, the known hosts file for JSch is a file listing the public keys of the SSH hosts, not the file listing their IP addresses (which is the Windows config file you are trying to supply here).

How does it work?


JSCH - SFPT Download File Example:


package zdemo;

/**
 *
 * @author hsalearn.blogspot.com
 */
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.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JSCH_SFTP_DOWNLOAD_EXAMPLE {

    public static void main(String[] args) {
        String SFTPHOST = "192.168.1.98";
        int SFTPPORT = 22;
        String SFTPUSER = "bnson";
        String SFTPPASS = "123456789";
        String SFTPWORKINGDIR = "/sftp/bnson/";
        //---------------
        Session session;
        Channel channel;
        ChannelSftp channelSftp;
        //---------------
        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);
            
            byte[] buffer = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(channelSftp.get("image_download.jpg"));
            
            File newFile = new File("D:\\tmp\\test\\image_download.jpg");
            OutputStream os = new FileOutputStream(newFile);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            
            int readCount;
            while ((readCount = bis.read(buffer)) > 0) {
                System.out.println("Writing: ");
                bos.write(buffer, 0, readCount);
            }
            
            bis.close();
            bos.close();
            System.out.println("Download success.");
        } catch (JSchException | SftpException | IOException ex) {
            Logger.getLogger(JSCH_SFTP_DOWNLOAD_EXAMPLE.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

JSCH - SFPT Upload File Example:

package zdemo;
/**
 *
 * @author bnson
 */
import java.io.File;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author hsalearn.blogspot.com
 *
 */
public class JSCH_SFTP_UPLOAD_EXAMPLE {

    public static void main(String[] args) {
        String SFTPHOST = "192.168.1.98";
        int SFTPPORT = 22;
        String SFTPUSER = "bnson";
        String SFTPPASS = "123456789";
        String SFTPWORKINGDIR = "/sftp/bnson/";
        String FILETOTRANSFER = "D:\\picture\\Girl\\001\\74258.jpg";
        //---------------
        Session session;
        Channel channel;
        ChannelSftp channelSftp;
        //---------------
        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());
            System.out.println("Upload success.");
        } catch (JSchException | SftpException | FileNotFoundException ex) {
            Logger.getLogger(JSCH_SFTP_UPLOAD_EXAMPLE.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}

JSCH - SFPT Download Folder Example:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package zdemo;

/**
 * @author http://hsalearn.blogspot.com
 */
import java.io.File;
import java.util.ArrayList;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JSCH_SFTP_DOWNLOAD_FOLDER_EXAMPLE {

    static ChannelSftp channelSftp = null;
    static Session session = null;
    static Channel channel = null;
    static String PATHSEPARATOR = "/";

    /**
     * @param args
     */
    public static void main(String[] args) {
        // SFTP Host Name or SFTP Host IP Address
        String SFTPHOST = "ftp.sps-delivery.de"; 
        // SFTP Port Number
        int SFTPPORT = 22; 
        // User Name
        String SFTPUSER = "userName"; 
        // Password
        String SFTPPASS = "Password"; 
        // Source Directory on SFTP server
        String SFTPWORKINGDIR = "/tmp/bnson/test"; 
        String LOCALDIRECTORY = "C:\\System\\bnson\\test\\download"; // Local Target Directory

        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);
            // Create SFTP Session
            session.connect(); 
            // Open SFTP Channel
            channel = session.openChannel("sftp"); 
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            // Change Directory on SFTP Server
            channelSftp.cd(SFTPWORKINGDIR); 

            recursiveFolderDownload(SFTPWORKINGDIR, LOCALDIRECTORY); // Recursive folder content download from SFTP server

        } catch (JSchException | SftpException ex) {
            Logger.getLogger(JSCH_SFTP_DOWNLOAD_FOLDER_EXAMPLE.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (channelSftp != null)
                channelSftp.disconnect();
            if (channel != null)
                channel.disconnect();
            if (session != null)
                session.disconnect();

        }

    }

    /**
     * This method is called recursively to download the folder content from SFTP server
     * 
     * @param sourcePath
     * @param destinationPath
     * @throws SftpException
     */
    @SuppressWarnings("unchecked")
    private static void recursiveFolderDownload(String sourcePath, String destinationPath) throws SftpException {
        // Let list of folder content
        List<ChannelSftp.LsEntry> fileAndFolderList = new ArrayList<>(channelSftp.ls(sourcePath)); 
        
        //Iterate through list of folder content
        for (ChannelSftp.LsEntry item : fileAndFolderList) {
            //Check if it is a file (not a directory).
            if (!item.getAttrs().isDir()) { 
                // Download only if changed later.
                if (!(new File(destinationPath + PATHSEPARATOR + item.getFilename())).exists() || (item.getAttrs().getMTime() > Long.valueOf(new File(destinationPath + PATHSEPARATOR + item.getFilename()).lastModified() / (long) 1000).intValue())) { 
                    File tmp = new File(destinationPath + PATHSEPARATOR + item.getFilename());
                    // Download file from source (source filename, destination filename).
                    channelSftp.get(sourcePath + PATHSEPARATOR + item.getFilename(), tmp.getAbsolutePath()); 
                }
            } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) {
                 // Empty folder copy.
                new File(destinationPath + PATHSEPARATOR + item.getFilename()).mkdirs();
                // Enter found folder on server to read its contents and create locally.
                recursiveFolderDownload(sourcePath + PATHSEPARATOR + item.getFilename(), destinationPath + PATHSEPARATOR + item.getFilename()); 
            }
        }
    }

}
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

 
Copyright © 2013. HSA Learn - All Rights Reserved
Template Created by ThemeXpose | Published By Gooyaabi Templates