Upload and download of sftp using Jcraft in Java

Source: Internet
Author: User
Tags ftp login

If you are familiar with Linux, you must be familiar with SSH,SFTP,SCP and other commands. SSH is a security protocol that is used in different systems or services

Secure connection between the converters. SSH encrypts all data during the connection and transfer process. Specific explanation, we can refer to the Baidu Encyclopedia of the text

File. Address: http://baike.baidu.com/view/16184.htm

But SSH is typically client-based or Linux command-line. For example, the client's tool: Openssh,putty,ssh

Tectia: On Linux, you can connect to the host you want to connect via SSH [email protected]. But if you are in a Java EE, how do you actually

Now SSH? Then can realize the function of scp,sftp? The Jsch described below can be implemented below.

Jsch is a purely Java library that implements SSH functionality in Java. The official address is:

http://www.jcraft.com/jsch/

The GitHub address is: Https://github.com/vngx/vngx-jsch

The MAVEN configuration is as follows:

<!--add SFTP dependency package--><dependency>    <groupId>com.jcraft</groupId>    <artifactId> Jsch</artifactid>    <version>0.1.51</version></dependency>

Below is a brief introduction to the following Jsch features:

1. Based on DSA and RSA encryption.

2. The 4 certification mechanism can be implemented. respectively:

Password
PublicKey (DSA,RSA)
Keyboard-interactive
Gss-api-with-mic

3. Generate Public/private key pair.

4. Execute scripts such as bash script

5. You can use HTTP/SOCK5 Proxy

6. Support Common SSH1 protocol and SSH2 protocol

Our daily use of Jsch is mainly based on password authentication and private key authentication.

Password-based authentication is relatively straightforward. The simple code is as follows:

Package Com.somnus.util.base;import Java.io.bytearrayinputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream; Import Java.util.properties;import java.util.vector;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Com.jcraft.jsch.channel;import Com.jcraft.jsch.channelsftp;import Com.jcraft.jsch.jsch;import Com.jcraft.jsch.session;import com.jcraft.jsch.sftpexception;/** * SFTP tool. Note: There are two methods of construction: password-based authentication, key-based authentication, respectively.  * * @see http://xliangwu.iteye.com/blog/1499764 * @author Somnus */public class Sftputil {private static final Logger    LOG = Loggerfactory.getlogger (Sftputil.class);    Private Channelsftp sftp; Private String UserName; FTP Login user name private String password; FTP login Password private string keyfilepath;//private key file path private string host; FTP server address IP address private int port;    FTP Port private Session sshsession; /** * Constructs a password-authenticated sftp Object * * @param userName *            Username * @param password * Login password * @param host * Server IP * @param port        * FWQ Port */public Sftputil (String userName, string password, string host, int port) {super ();        This.username = UserName;        This.password = password;        This.host = host;    This.port = port;     /** * Constructs an SFTP object based on key authentication * * @param userName * username * @param host * Server IP  * @param port * FWQ ports * @param keyfilepath * Private Key file path */public Sftputil (String        UserName, string host, int port, string keyfilepath) {super ();        This.username = UserName;        This.host = host;        This.port = port;    This.keyfilepath = Keyfilepath;            /** * Connect SFTP Server * * @throws Exception */public void Connect () throws Exception {try {            Jsch Jsch = new Jsch ();     if (Keyfilepath! = null) {           Jsch.addidentity (Keyfilepath);//Set Private key Log.info ("Connect sftp, private key file path:" + Keyfilepath); } log.info ("SFTP Host:" + Host + ";            UserName: "+ userName);            Sshsession = Jsch.getsession (userName, host, Port);            Log.debug ("Session has been established.");            if (password! = null) {Sshsession.setpassword (password);            } Properties Sshconfig = new properties ();            Sshconfig.put ("stricthostkeychecking", "no");            Sshsession.setconfig (Sshconfig);            Sshsession.connect ();            Log.debug ("Session is connected.");            Channel channel = Sshsession.openchannel ("sftp");            Channel.connect ();            SFTP = (channelsftp) channel; Log.info ("Connect to SFTP successfully.        Host: "+ Host"; } catch (Exception e) {log.error ("Connection SFTP failed!            ", e);        Throw e; }}/** * Close connection Server * * public void disconnect () {if (sftp! = null) {if (SFTp.isconnected ()) {sftp.disconnect ();                Sshsession.disconnect (); Log.info ("SFTP Connection closed successfully!            "+ sftp); } else if (sftp.isclosed ()) {Log.warn ("SFTP is closed and does not need to be closed repeatedly!")            "+ sftp); }}}/** * Upload data from the input stream to SFTP as a file * * @param directory * uploaded to the directory * @param sftpfil ename * SFTP file name * @param in * input stream * @throws Exception */public void upload ( String directory, string sftpfilename, InputStream input) throws Exception {try {try {///If the CD report is abnormal, the directory does not            exist, create the directory sftp.cd (directory);                } catch (Exception e) {sftp.mkdir (directory);            SFTP.CD (directory);            } sftp.put (input, sftpfilename); Log.info ("SFTP upload succeeded!        File name: "+ sftpfilename); } catch (Exception e) {log.error ("SFTP upload failed!            File name "+ Sftpfilename, E);        Throw e; }    }    /**     * Upload Individual files * * @param directory * upload to sftp directory * @param uploadfile * file to upload, including road  Path * @throws Exception */public void upload (string directory, String uploadfile) throws Exception {File        File = new file (uploadfile);    Upload (directory, File.getname (), new FileInputStream (file)); }/** * Upload byte[] to sftp as a file.     Note: Generate byte[from string] Yes, to specify a character set. * * @param directory * upload to sftp directory * @param sftpfilename * file name on the sftp side * @param b Ytearr * byte array to upload * @throws Exception */public void upload (string directory, String Sftpfilenam    E, byte[] bytearr) throws Exception {upload (directory, sftpfilename, new Bytearrayinputstream (Bytearr));     /** * Upload the string to the SFTP * * @param directory * to the SFTP directory * @param the specified character encoding * Sftpfilename    * File name on the sftp side * @param datastr * data to be uploaded * @param charsetname *        Files on SFTP, saved by the character encoding * @throws Exception */public void upload (string directory, String sftpfilename, Stri Ng Datastr, String charsetname) throws exception{upload (directory, sftpfilename, new Bytearrayinputstream (Datastr.    GetBytes (CharsetName));     /** * Download File * * @param directory * Download directory * @param downloadFile * Download file * @param saveFile * There is a local path * @throws Exception */public void Download (String directory, STR ing downloadFile, String saveFile) throws Exception {try {if (directory! = null &&! ").            Equals (directory)) {sftp.cd (directory);            } File File = new file (saveFile);            Sftp.get (DownloadFile, new FileOutputStream (file)); Log.info ("sftp download file succeeded!        FileName "+ downloadFile); } catch (Exception e) {log.error ("sftp download file failed!            File name: "+ DownloadFile, E);        Throw e; }}/** * download* @param directory Download directory * @param downloadFile downloaded file name * @return byte array * @throws Exception */Public        byte[] Download (string directory, String downloadFile) throws exception{byte[] fileData = null; try {if (directory! = null &&! ").            Equals (directory)) {sftp.cd (directory);                        } InputStream is = Sftp.get (downloadFile);            FileData = new byte[is.available ()];                        Is.read (FileData); Log.info ("sftp download file succeeded!        FileName "+ downloadFile); } catch (Sftpexception e) {log.error ("sftp download file failed!            File name: "+ DownloadFile, E);        Throw e; } catch (IOException e) {log.error ("sftp download file read failed!            File name: "+ DownloadFile, E);        Throw e;    } return fileData; }/** * Delete files * * @param directory * To delete the directory where the files are located * @param deletefile * to delete FILE * @throws Exception */public voidDelete (string directory, String deletefile) throws Exception {try {sftp.cd (directory);        SFTP.RM (DeleteFile);            } catch (Exception e) {log.error ("sftp Delete file failed" + DeleteFile, E);        Throw e; }}/** * List files under directory * * @param directory * directories to list * @param sftp * @return * @ Throws Sftpexception */public Vector listfiles (String directory) throws sftpexception {return sftp.ls (dire    Ctory); }}


Upload and download of sftp using Jcraft in Java

Related Article

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.