Use the jsch package, SFTP and SSH2 file operations and remote command execution in Java

Source: Internet
Author: User

Sftpconstants. Java, which defines some parameter names we need:

 

public class SFTPConstants {    public static final String SFTP_REQ_HOST = "host";    public static final String SFTP_REQ_PORT = "port";    public static final String SFTP_REQ_USERNAME = "username";    public static final String SFTP_REQ_PASSWORD = "password";    public static final int SFTP_DEFAULT_PORT = 22;    public static final String SFTP_REQ_LOC = "location";}

Sftpchannel. Java we use it to obtain channel objects:

 

 

Import Java. util. map; import Java. util. properties; import Org. apache. log4j. logger; import COM. jcraft. jsch. channel; import COM. jcraft. jsch. jsch; import COM. jcraft. jsch. jschexception; import COM. jcraft. jsch. session; public class sftpchannel {session = NULL; channel = NULL; Private Static final logger log = logger. getlogger (sftpchannel. class); public channel getchannel (string name, Map <strin G, string> sftpdetails, int timeout) throws jschexception {string ftphost = sftpdetails. get (sftpconstants. sftp_req_host); string port = sftpdetails. get (sftpconstants. sftp_req_port); string ftpusername = sftpdetails. get (sftpconstants. sftp_req_username); string ftppassword = sftpdetails. get (sftpconstants. sftp_req_password); int ftpport = sftpconstants. sftp_default_port; If (port! = NULL &&! Port. equals ("") {ftpport = integer. valueof (port);} jsch = new jsch (); // create jsch object session = jsch. getsession (ftpusername, ftphost, ftpport); // obtain a session object log.info ("session created. "); If (ftppassword! = NULL) {session. setpassword (ftppassword); // set the password} properties Config = new properties (); config. put ("stricthostkeychecking", "no"); Session. setconfig (config); // set properties session for the session object. setTimeout (timeout); // sets the timeout time session. connect (); // establish the link log.info ("session connected. "); log.info (" Opening channel. "); Channel = session. openchannel (name); // open the SFTP channel log.info ("connected Su Ccessfully to ftphost = "+ ftphost +", as ftpusername = "+ ftpusername +", returning: "+ channel); return channel;} public void connect () throws jschexception {channel. connect ();} public void closechannel () throws exception {If (Channel! = NULL) {channel. Disconnect ();} If (session! = NULL) {session. Disconnect ();}}

Create a class to monitor the progress of file operations:

 

 

import com.jcraft.jsch.SftpProgressMonitor;public class FileProgressMonitor implements SftpProgressMonitor {    private long transfered;        public FileProgressMonitor()    {    }        @Override    public boolean count(long count) {        transfered = transfered + count;        System.out.println("Currently transferred total size: " + transfered + " bytes");        return true;    }    @Override    public void end() {    System.out.println("Transferring done.");    }    @Override    public void init(int op, String src, String dest, long max) {    System.out.println("Transferring begin.");    }}

Next, let's take a look at file operations:

 

 

 
Map <string, string> sftpdetails = new hashmap <string, string> (); sftpdetails. put (sftpconstants. sftp_req_host, "192.168.1.17"); sftpdetails. put (sftpconstants. sftp_req_username, "root"); sftpdetails. put (sftpconstants. sftp_req_password, "123456"); sftpdetails. put (sftpconstants. sftp_req_port, "22"); string src = "/home/test.txt"; // target file name string DST = "test/test.txt "; // local file name sftpchannel channel = new sftpchannel (); channelsftp chsftp = NULL; try {chsftp = (channelsftp) channel. getchannel ("SFTP", sftpdetails, 60000); channel. connect (); chsftp. get (SRC, DST, new fileprogressmonitor (), channelsftp. overwrite);} catch (jschexception e) {e. printstacktrace ();} catch (exception e) {e. printstacktrace ();} finally {chsftp. quit (); channel. closechannel ();}

Run the following remote command:

 

 

String charset = "UTF-8";String cmd = "ls";Map<String, String> sftpDetails = new HashMap<String, String>();sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "192.168.1.17");sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "root");sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "123456");sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");SFTPChannel channel = new SFTPChannel();ChannelExec execChannel = null;execChannel = (ChannelExec)channel.getChannel("exec", sftpDetails, 60000);execChannel.setCommand(cmd);execChannel.setInputStream(null);execChannel.setErrStream(System.err);execChannel.connect();InputStream in = execChannel.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));String buf = null;while ((buf = reader.readLine()) != null){//System.out.println(buf);}reader.close();try {channel.closeChannel();} catch (Exception e) {e.printStackTrace();}

After testing, jsch is still very stable and suitable for use in projects. This tool is used for file operations and remote command execution between machines.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.