package com.sssppp.Communication;/** * This program will demonstrate the sftp protocol support. * $ CLASSPATH=.:../build javac Sftp.java * $ CLASSPATH=.:../build java Sftp * You will be asked username, host and passwd. * If everything works fine, you will get a prompt 'sftp>'. * 'help' command will show available command. * In current implementation, the destination path for 'get' and 'put' * commands must be a file, not a directory. * */import java.util.HashMap;import java.util.Map;import java.util.Properties;import javax.swing.ProgressMonitor;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.SftpProgressMonitor;/** * <pre> * ----------命令集合--------------------- * 可參考連接(官方示例程序):http://www.jcraft.com/jsch/examples/Sftp.java * ChannelSftp c = (ChannelSftp) channel; * c.quit(); * c.exit(); * c.cd("/home/example"); * c.lcd("/home/example"); * c.rm("/home/example.gz"); * c.rmdir("/home/example"); * c.mkdir("/home/example"); * c.chgrp(777, "/home/example"); * c.chown(777, "/home/example"); * c.chmod(777, "/home/example"); * c.pwd(); * c.lpwd(); * c.ls("/home/example"); * * SftpProgressMonitor monitor = new MyProgressMonitor(); //顯示進度 * //文件下載 * c.get("srcPath", "dstPath", monitor, ChannelSftp.OVERWRITE); * c.get("srcPath", "dstPath", monitor, ChannelSftp.RESUME); //斷點續傳 * c.get("srcPath", "dstPath", monitor, ChannelSftp.APPEND); * //文件上傳 * c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND); * c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND); * c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND); * * c.hardlink("oldPath", "newPath"); * c.rename("oldPath", "newPath"); * c.symlink("oldPath", "newPath"); * c.readlink("Path"); * c.realpath("Path"); * c.version(); * * SftpStatVFS stat = c.statVFS("path"); //df 命令 * long size = stat.getSize(); * long used = stat.getUsed(); * long avail = stat.getAvailForNonRoot(); * long root_avail = stat.getAvail(); * long capacity = stat.getCapacity(); * * c.stat("path"); * c.lstat("path"); * ---------------------------------------------------------------------- * </pre> * */public class SftpUtil { Session session = null; Channel channel = null; 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"; /** * 測試程序 * @param arg * @throws Exception */ public static void main(String[] arg) throws Exception { // 設置主機ip,端口,用戶名,密碼 Map<String, String> sftpDetails = new HashMap<String, String>(); sftpDetails.put(SFTP_REQ_HOST, "10.180.137.221"); sftpDetails.put(SFTP_REQ_USERNAME, "root"); sftpDetails.put(SFTP_REQ_PASSWORD, "xxxx"); sftpDetails.put(SFTP_REQ_PORT, "22"); //測試文件上傳 String src = "C:\\xxx\\TMP\\site-1.10.4.zip"; // 本地文件名 String dst = "/tmp/sftp/"; // 目標文件名 uploadFile(src, dst, sftpDetails); //測試文件下載 String srcFilename = "/tmp/sftp/site-1.10.4.zip"; String dstFilename = "C:\\tmp\\site-1.10.4-new.zip"; downloadFile(srcFilename, dstFilename, sftpDetails); } public static void downloadFile(String src, String dst, Map<String, String> sftpDetails) throws Exception { SftpUtil sftpUtil = new SftpUtil(); ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 160000); // Retrieves the file attributes of a file or directory // SftpATTRS attr = chSftp.stat(src); // long fileSize = attr.getSize(); //代碼段1/代碼段2/代碼段3:分別演示瞭如何使用JSch的各類put方法來進行文件下載 try { // 代碼段1:使用這個方法時,dst能夠是目錄,若dst爲目錄,則下載到本地的文件名將與src文件名相同 chSftp.get(src, dst, new MyProgressMonitor(),ChannelSftp.RESUME); //斷點續傳 /*** OutputStream out = new FileOutputStream(dst); // 代碼段2:將目標服務器上文件名爲src的文件下載到本地的一個輸出流對象,該輸出流爲一個文件輸出流 chSftp.get(src, out, new MyProgressMonitor()); // 代碼段3:採用讀取get方法返回的輸入流數據的方式來下載文件 InputStream is = chSftp.get(src, new MyProgressMonitor(),ChannelSftp.RESUME); byte[] buff = new byte[1024 * 2]; int read; if (is != null) { do { read = is.read(buff, 0, buff.length); if (read > 0) { out.write(buff, 0, read); } out.flush(); } while (read >= 0); } **/ } catch (Exception e) { e.printStackTrace(); } finally { chSftp.quit(); sftpUtil.closeChannel(); } } public static void uploadFile(String src, String dst, Map<String, String> sftpDetails) throws Exception { SftpUtil sftpUtil = new SftpUtil(); ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 60000); /** * 代碼段1/代碼段2/代碼段3分別演示瞭如何使用JSch的不一樣的put方法來進行文件上傳。這三段代碼實現的功能是同樣的, * 都是將本地的文件src上傳到了服務器的dst文件 */ /**代碼段1 OutputStream out = chSftp.put(dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式 byte[] buff = new byte[1024 * 256]; // 設定每次傳輸的數據塊大小爲256KB int read; if (out != null) { InputStream is = new FileInputStream(src); do { read = is.read(buff, 0, buff.length); if (read > 0) { out.write(buff, 0, read); } out.flush(); } while (read >= 0); } **/ // 使用這個方法時,dst能夠是目錄,當dst是目錄時,上傳後的目標文件名將與src文件名相同 // ChannelSftp.RESUME:斷點續傳 chSftp.put(src, dst, new MyProgressMonitor(), ChannelSftp.RESUME); // 代碼段2 // 將本地文件名爲src的文件輸入流上傳到目標服務器,目標文件名爲dst。 // chSftp.put(new FileInputStream(src), dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 代碼段3 chSftp.quit(); sftpUtil.closeChannel(); } /** * 根據ip,用戶名及密碼獲得一個SFTP * channel對象,即ChannelSftp的實例對象,在應用程序中就能夠使用該對象來調用SFTP的各類操做方法 * * @param sftpDetails * @param timeout * @return * @throws JSchException */ public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException { String ftpHost = sftpDetails.get(SFTP_REQ_HOST); String port = sftpDetails.get(SFTP_REQ_PORT); String ftpUserName = sftpDetails.get(SFTP_REQ_USERNAME); String ftpPassword = sftpDetails.get(SFTP_REQ_PASSWORD); int ftpPort = SFTP_DEFAULT_PORT; if (port != null && !port.equals("")) { ftpPort = Integer.valueOf(port); } JSch jsch = new JSch(); // 建立JSch對象 session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根據用戶名,主機ip,端口獲取一個Session對象 if (ftpPassword != null) { session.setPassword(ftpPassword); // 設置密碼 } Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 爲Session對象設置properties session.setTimeout(timeout); // 設置timeout時間 session.connect(5000); // 經過Session創建連接 channel = session.openChannel("sftp"); // 打開SFTP通道 channel.connect(); // 創建SFTP通道的鏈接 return (ChannelSftp) channel; } public void closeChannel() throws Exception { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } /** * 進度監控器-JSch每次傳輸一個數據塊,就會調用count方法來實現主動進度通知 * */ public static class MyProgressMonitor implements SftpProgressMonitor { private long count = 0; //當前接收的總字節數 private long max = 0; //最終文件大小 private long percent = -1; //進度 /** * 當每次傳輸了一個數據塊後,調用count方法,count方法的參數爲這一次傳輸的數據塊大小 */ @Override public boolean count(long count) { this.count += count; if (percent >= this.count * 100 / max) { return true; } percent = this.count * 100 / max; System.out.println("Completed " + this.count + "(" + percent + "%) out of " + max + "."); return true; } /** * 當傳輸結束時,調用end方法 */ @Override public void end() { System.out.println("Transferring done."); } /** * 當文件開始傳輸時,調用init方法 */ @Override public void init(int op, String src, String dest, long max) { if (op==SftpProgressMonitor.PUT) { System.out.println("Upload file begin."); }else { System.out.println("Download file begin."); } this.max = max; this.count = 0; this.percent = -1; } } /** * 官方提供的進度監控器 * */ public static class DemoProgressMonitor implements SftpProgressMonitor { ProgressMonitor monitor; long count = 0; long max = 0; /** * 當文件開始傳輸時,調用init方法。 */ public void init(int op, String src, String dest, long max) { this.max = max; monitor = new ProgressMonitor(null, ((op == SftpProgressMonitor.PUT) ? "put" : "get") + ": " + src, "", 0, (int) max); count = 0; percent = -1; monitor.setProgress((int) this.count); monitor.setMillisToDecideToPopup(1000); } private long percent = -1; /** * 當每次傳輸了一個數據塊後,調用count方法,count方法的參數爲這一次傳輸的數據塊大小。 */ public boolean count(long count) { this.count += count; if (percent >= this.count * 100 / max) { return true; } percent = this.count * 100 / max; monitor.setNote("Completed " + this.count + "(" + percent + "%) out of " + max + "."); monitor.setProgress((int) this.count); return !(monitor.isCanceled()); } /** * 當傳輸結束時,調用end方法。 */ public void end() { monitor.close(); } }}