TUYỂN DỤNG

[Programming][Java] Secure Channel (JSCH ).

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()); 
            }
        }
    }

}

COMMENTS

Name

Anime,1,Application,6,Articles,6,Audio,2,Database,4,ElasticSearch,1,FFmpeg,1,Java,6,JavaScript,1,Links,2,Model,3,MS-SQL,3,Notepad++,1,Pictures,4,Programming,7,Projects,3,SPS,3,SQL,4,System,1,Truyện,2,Windows 10,1,YouTube,1,
ltr
item
Bùi Ngọc Sơn: [Programming][Java] Secure Channel (JSCH ).
[Programming][Java] Secure Channel (JSCH ).
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTd4OPi5ZrV-oxEuA41Ch3YTQ4-D3lZUnJQkRlHBh1C-jBXKksAxSPi6CG8VgW6QErsC4l6U4HVzrIonrdi73-n5cU51uDvG24hHJlIk6Y7frHDcqcfmzVQ6D5MDYBBBBRtMTTt3064BMr/s1600/JSCH_WORKING.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTd4OPi5ZrV-oxEuA41Ch3YTQ4-D3lZUnJQkRlHBh1C-jBXKksAxSPi6CG8VgW6QErsC4l6U4HVzrIonrdi73-n5cU51uDvG24hHJlIk6Y7frHDcqcfmzVQ6D5MDYBBBBRtMTTt3064BMr/s72-c/JSCH_WORKING.png
Bùi Ngọc Sơn
https://bnson1986.blogspot.com/2019/11/java-secure-channel-jsch.html
https://bnson1986.blogspot.com/
http://bnson1986.blogspot.com/
http://bnson1986.blogspot.com/2019/11/java-secure-channel-jsch.html
true
7468510552861380973
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content