项目中经常要做上传功能,除了页面使用上传组件外,后台的文件处理一种是 存放在项目中文件夹,另一种存放部署的服务器中,后一种更灵活对项目更友好。
JSch是Java Secure Channel的缩写。
JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。
本文只介绍如何使用JSch实现的SFTP功能。
SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。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协议连接。