Java中使用jcraft進行SFTP的上傳下載

來源:互聯網
上載者:User

標籤:java   ssh   sftp   上傳   下載   

如果大家熟悉Linux的話,一定對ssh,sftp,scp等命令非常熟悉。ssh是一個安全性通訊協定,用來在不同系統或者服務

器之間進行安全連線。ssh 在串連和傳送的過程中會加密所有的資料。具體的解釋,大家可以參考百度百科的文

檔。地址為:http://baike.baidu.com/view/16184.htm

    但是SSH一般是基於用戶端的或者Linux命令列的。比如用戶端的工具:OpenSSH,putty,SSH 

Tectia;在linux上大家可以通過ssh [email protected]串連到所要想串連的主機。但是如果在J2EE中,如何實

現SSH呢?進而可以實現SCP,SFTP的功能呢?下面介紹的JSCH就可以實現下邊的功能。

    JSCH是一個純粹的用java實現SSH功能的java  library. 官方地址為:

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

GitHub 地址為:https://github.com/vngx/vngx-jsch

maven配置如下:

<!-- 加入sftp依賴包 --><dependency>    <groupId>com.jcraft</groupId>    <artifactId>jsch</artifactId>    <version>0.1.51</version></dependency>

下面簡單介紹下JSCH的特點:

1.基於DSA和RSA加密。

2.可以實現4中認證機制。分別是:

password
publickey(DSA,RSA)
keyboard-interactive
gss-api-with-mic

3.產生public/private key pair.

4.執行bash script 等指令碼

5.可以通過HTTP/SOCK5 proxy

6.支援常見SSH1協議和SSH2協議

我們日常用到的JSCH主要是基於是密碼認證和private key 認證。

基於密碼認證的比較簡單。簡單代碼如下:

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工具。注意:構造方法有兩個:分別是基於密碼認證、基於秘鑰認證。 *  * @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 登入使用者名稱    private String password; // FTP 登入密碼    private String keyFilePath;// 私密金鑰檔案的路徑    private String host; // FTP 伺服器位址IP地址    private int port; // FTP 連接埠    private Session sshSession;    /**     * 構造基於密碼認證的sftp對象     *      * @param userName     *            使用者名稱     * @param password     *            登陸密碼     * @param host     *            伺服器ip     * @param port     *            fwq連接埠     */    public SFTPUtil(String userName, String password, String host, int port) {        super();        this.userName = userName;        this.password = password;        this.host = host;        this.port = port;    }    /**     * 構造基於秘鑰認證的sftp對象     *      * @param userName     *            使用者名稱     * @param host     *            伺服器ip     * @param port     *            fwq連接埠     * @param keyFilePath     *            私密金鑰檔案路徑     */    public SFTPUtil(String userName, String host, int port, String keyFilePath) {        super();        this.userName = userName;        this.host = host;        this.port = port;        this.keyFilePath = keyFilePath;    }    /**     * 串連sftp伺服器     *      * @throws Exception     */    public void connect() throws Exception {        try {            JSch jsch = new JSch();            if (keyFilePath != null) {                jsch.addIdentity(keyFilePath);// 設定私密金鑰                LOG.info("串連sftp,私密金鑰檔案路徑:" + keyFilePath);            }            LOG.info("sftp host: " + host + "; userName:" + userName);            sshSession = jsch.getSession(userName, host, port);            LOG.debug("Session 已建立.");            if (password != null) {                sshSession.setPassword(password);            }            Properties sshConfig = new Properties();            sshConfig.put("StrictHostKeyChecking", "no");            sshSession.setConfig(sshConfig);            sshSession.connect();            LOG.debug("Session 已串連.");            Channel channel = sshSession.openChannel("sftp");            channel.connect();            sftp = (ChannelSftp) channel;            LOG.info("串連到SFTP成功。host: " + host);        } catch (Exception e) {            LOG.error("串連sftp失敗!", e);            throw e;        }    }    /**     * 關閉串連 server     */    public void disconnect() {        if (sftp != null) {            if (sftp.isConnected()) {                sftp.disconnect();                sshSession.disconnect();                LOG.info("sftp串連關閉成功!" + sftp);            } else if (sftp.isClosed()) {                LOG.warn("sftp 已經關閉,不需要重複關閉!" + sftp);            }        }    }    /**     * 將輸入資料流的資料上傳到sftp作為檔案     *      * @param directory     *            上傳到該目錄     * @param sftpFileName     *            sftp端檔案名稱     * @param in     *            輸入資料流     * @throws Exception     */    public void upload(String directory, String sftpFileName, InputStream input) throws Exception {        try {            try {// 如果cd報異常,說明目錄不存在,就建立目錄                sftp.cd(directory);            } catch (Exception e) {                sftp.mkdir(directory);                sftp.cd(directory);            }            sftp.put(input, sftpFileName);            LOG.info("sftp上傳成功!檔案名稱:" + sftpFileName);        } catch (Exception e) {            LOG.error("sftp上傳失敗!檔案名稱" + sftpFileName, e);            throw e;        }    }    /**     * 上傳單個檔案     *      * @param directory     *            上傳到sftp目錄     * @param uploadFile     *            要上傳的檔案,包括路徑     * @throws Exception     */    public void upload(String directory, String uploadFile) throws Exception {        File file = new File(uploadFile);        upload(directory, file.getName(), new FileInputStream(file));    }    /**     * 將byte[]上傳到sftp,作為檔案。注意:從String產生byte[]是,要指定字元集。     *      * @param directory     *            上傳到sftp目錄     * @param sftpFileName     *            檔案在sftp端的命名     * @param byteArr     *            要上傳的位元組數組     * @throws Exception     */    public void upload(String directory, String sftpFileName, byte[] byteArr) throws Exception {        upload(directory, sftpFileName, new ByteArrayInputStream(byteArr));    }    /**     * 將字串按照指定的字元編碼上傳到sftp     *      * @param directory     *            上傳到sftp目錄     * @param sftpFileName     *            檔案在sftp端的命名     * @param dataStr     *            待上傳的資料     * @param charsetName     *            sftp上的檔案,按該字元編碼儲存     * @throws Exception     */    public void upload(String directory, String sftpFileName, String dataStr, String charsetName) throws Exception{        upload(directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));    }    /**     * 下載檔案     *      * @param directory     *            下載目錄     * @param downloadFile     *            下載的檔案     * @param saveFile     *            存在本地的路徑     * @throws Exception     */    public void download(String directory, String 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下載檔案成功!檔案名稱" + downloadFile);        } catch (Exception e) {            LOG.error("sftp下載檔案失敗!檔案名稱:" + downloadFile, e);            throw e;        }    }    /**     * 下載檔案     * @param directory 下載目錄     * @param downloadFile 下載的檔案名稱     * @return 位元組數組     * @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下載檔案成功!檔案名稱" + downloadFile);        } catch (SftpException e) {            LOG.error("sftp下載檔案失敗!檔案名稱:" + downloadFile, e);            throw e;        } catch (IOException e) {            LOG.error("sftp下載檔案讀取失敗!檔案名稱:" + downloadFile, e);            throw e;        }        return fileData;    }    /**     * 刪除檔案     *      * @param directory     *            要刪除檔案所在目錄     * @param deleteFile     *            要刪除的檔案     * @throws Exception     */    public void delete(String directory, String deleteFile) throws Exception {        try {            sftp.cd(directory);            sftp.rm(deleteFile);        } catch (Exception e) {            LOG.error("sftp刪除檔案失敗" + deleteFile, e);            throw e;        }    }    /**     * 列出目錄下的檔案     *      * @param directory     *            要列出的目錄     * @param sftp     * @return     * @throws SftpException     */    public Vector listFiles(String directory) throws SftpException {        return sftp.ls(directory);    }}


Java中使用jcraft進行SFTP的上傳下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.