項目中經常要做上傳功能,除了頁面使用上傳組件外,后臺的文件處理一種是 存放在項目中文件夾,另一種存放部署的服務器中,后一種更靈活對項目更友好。
JSch是java Secure Channel的縮寫。JSch是一個SSH2的純Java實現。它允許你連接到一個SSH服務器,并且可以使用端口轉發,X11轉發,文件傳輸等,當然你也可以集成它的功能到你自己的應用程序。 本文只介紹如何使用JSch實現的SFTP功能。 SFTP是Secure File Transfer PRotocol的縮寫,安全文件傳送協議??梢詾閭鬏斘募峁┮环N安全的加密方法。SFTP 為 SSH的一部份,是一種傳輸文件到服務器的安全方式。SFTP是使用加密傳輸認證信息和傳輸的數據,所以,使用SFTP是非常安全的。但是,由于這種傳輸方式使用了加密/解密技術,所以傳輸效率比普通的FTP要低得多,如果您對網絡安全性要求更高時,可以使用SFTP代替FTP。(來自百度的解釋) 要使用JSch,需要下載它的jar包,請從官網下載它:http://www.jcraft.com/jsch/ ChannelSftp類是JSch實現SFTP核心類,它包含了所有SFTP的方法,如:put(): 文件上傳get(): 文件下載cd(): 進入指定目錄ls(): 得到指定目錄下的文件列表rename(): 重命名指定文件或目錄rm(): 刪除指定文件mkdir(): 創建目錄rmdir(): 刪除目錄以下是stfpUtils工具類的方法package com.pzedu.infrastructure.common.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.Properties;import java.util.Vector;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.ChannelSftp.LsEntry;import com.jcraft.jsch.JSch;import com.jcraft.jsch.session;import com.jcraft.jsch.SftpException;/** * sftp 工具類 * * @author weird */public final class Sftps { private static final Logger log = LoggerFactory.getLogger(Sftps.class); private Session sshSession; private ChannelSftp sftp; /** * 連接sftp服務器 * @param host * @param port * @param username * @param passWord * @return * @throws Exception */ public ChannelSftp connect(String host, int port, String username, String password) throws Exception { JSch jsch = new JSch(); sshSession = jsch.getSession(username, host, port); log.debug("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); log.debug("Session connected."); log.debug("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; log.debug("Connected to " + host + "."); return sftp; } /** * 連接sftp服務器 * @param host * @param port * @param username * @param privateKey * @param passphrase * @return * @throws Exception */ public ChannelSftp connect(String host, int port, String username, String privateKey ,String passphrase) throws Exception { JSch jsch = new JSch(); //設置密鑰和密碼 if (!StringUtils.isEmpty(privateKey)) { if (!StringUtils.isEmpty(passphrase)) { //設置帶口令的密鑰 jsch.addIdentity(privateKey, passphrase); } else { //設置不帶口令的密鑰 jsch.addIdentity(privateKey); } } sshSession = jsch.getSession(username, host, port); log.debug("Session created."); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); log.debug("Session connected."); log.debug("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; log.debug("Connected to " + host + "."); return sftp; } public void portForwardingL(int lport, String rhost, int rport) throws Exception { int assinged_port = sshSession.setPortForwardingL(lport, rhost, rport); System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport); } /** * 斷開連接 */ public void disconnect() { if (sftp != null) sftp.disconnect(); if (sshSession != null) sshSession.disconnect(); } /** * 上傳文件 * * @param directory * 上傳的目錄 * @param uploadFile * 要上傳的文件 * @param sftp */ public void upload(String directory, String uploadFile) throws Exception { sftp.cd(directory); File file = new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); } public void upload(String directory, File file) throws Exception { sftp.cd(directory); sftp.put(new FileInputStream(file), file.getName()); System.out.println("upload file "+file.getAbsolutePath() + " to host " + sshSession.getHost()); } public void uploadDir(File src, String dst) throws Exception { if (!exist(dst)) { sftp.mkdir(dst); } if (src.isFile()) { upload(dst, src); } else { for (File file : src.listFiles()) { if (file.isDirectory()) { uploadDir(file, dst + "/" + file.getName()); } upload(dst, file); } } } /** * 目錄是否查找 * @param path * @return * @throws SftpException */ public boolean exist(String path) throws SftpException { String pwd = sftp.pwd(); try { sftp.cd(path); } catch (SftpException e) { if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) { return false; } else { throw e; } } finally { sftp.cd(pwd); } return true; } /** * 下載文件 * @param directory * @param downloadFile * @param saveFile * @throws Exception */ public void download(String directory, String downloadFile, String saveFile) throws Exception { sftp.cd(directory); File file = new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); } /** * 下載文件 * @param directory * @param downloadFile * @param saveFile * @throws Exception */ public void download(String directory, String downloadFile, File saveFile) throws Exception { sftp.cd(directory); sftp.get(downloadFile, new FileOutputStream(saveFile)); System.out.println("download file "+directory + "/" +downloadFile + " from host " + sshSession.getHost()); } /** * 下載文件 * @param src * @param dst * @throws Exception */ @SuppressWarnings("unchecked") public void downloadDir(String src, File dst) throws Exception { try { sftp.cd(src); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } dst.mkdirs(); Vector<LsEntry> files = sftp.ls(src); for (LsEntry lsEntry : files) { if (lsEntry.getFilename().equals(".") || lsEntry.getFilename().equals("..")) { continue; } if (lsEntry.getLongname().startsWith("d")) { downloadDir(src + "/" + lsEntry.getFilename(), new File(dst, lsEntry.getFilename())); } else { download(src, lsEntry.getFilename(), new File(dst, lsEntry.getFilename())); } } } /** * 刪除文件 * @param directory * @param deleteFile * @throws SftpException */ public void delete(String directory, String deleteFile) throws SftpException { sftp.cd(directory); sftp.rm(deleteFile); } /** * 列出目錄下的文件 * @param directory * @return * @throws SftpException */ public Vector listFiles(String directory) throws SftpException { return sftp.ls(directory); } public static void main(String[] args) throws Exception { Sftps sf = new Sftps(); String host = "192.168.56.101"; int port = 22; String username = "root"; String password = "123"; String privateKey = "C:/Users/Administrator/Desktop/seRT_SSH_key/front/Identity"; String passphrase = "h$VgBrx3nhwH#2!h6zs0uGhzcCX8dTPa"; String src = "/usr/local/apache-tomcat-7.0.63/webapps/pzedu"; sf.connect(host, port, username, privateKey, passphrase); sf.portForwardingL(1194, "10.169.97.248", 1194); // ChannelSftp sftp = sf.connect(host, port, username, password);// sf.upload(directory, uploadFile, sftp);// sf.download(directory, downloadFile, saveFile, sftp);// sf.delete(directory, deleteFile, sftp); // try {//// Vector files = sf.listFiles("/root");// sf.downloadDir(src, new File("C:/staticsfile"));//// sf.uploadDir(new File("C:/staticsfile"), "/root/temp");// System.out.println("finished");// sftp.disconnect();// } catch (Exception e) {// e.printStackTrace();// }// sf.disconnect(); } public Session getSshSession() { return sshSession; } public ChannelSftp getSftp() { return sftp; }}采用的是stfp協議連接。
新聞熱點
疑難解答