JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器。
Maven所需的包:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.51</version>
</dependency>
<!-- jsch 所依赖的jar包 -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jzlib</artifactId>
<version>1.0.7</version>
</dependency>
//工具类代码
public class SFTPUtils {
private static Logger log = LoggerFactory.getLogger(SFTPUtils.class.getName());
private String host;//服务器连接ip
private String username;//用户名
private String password;//密码
private int port = 22;//端口号
private ChannelSftp sftp = null;
private Session sshSession = null;
public SFTPUtils(){}
public SFTPUtils(String host, int port, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
this.port = port;
}
public SFTPUtils(String host, String username, String password)
{
this.host = host;
this.username = username;
this.password = password;
}
/**
* 通过SFTP连接服务器
*/
public void connect() {
try
{
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
if (log.isInfoEnabled())
{
log.info("Session created.");
}
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
if (log.isInfoEnabled())
{
log.info("Session connected.");
}
Channel channel = sshSession.openChannel("sftp");
channel.connect();
if (log.isInfoEnabled())
{
log.info("Opening Channel.");
}
sftp = (ChannelSftp) channel;
if (log.isInfoEnabled())
{
log.info("Connected to " + host + ".");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
if (log.isInfoEnabled())
{
log.info("sftp is closed already");
}
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected())
{
this.sshSession.disconnect();
if (log.isInfoEnabled())
{
log.info("sshSession is closed already");
}
}
}
}
/**
* 批量下载文件
* @param remotePath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式)
* @param del:下载后是否删除sftp文件
* @return
*/
public List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del) {
List<String> filenames = new ArrayList<String>();
try {
Vector v = listFiles(remotePath);
// sftp.cd(remotePath);
if (v.size() > 0)
{
System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
Iterator it = v.iterator();
while (it.hasNext())
{
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir())
{
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat.trim();
fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();
// 三种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0)
{
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat))
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileFormat.length() > 0 && "".equals(fileEndFormat))
{
if (filename.startsWith(fileFormat))
{
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileEndFormat.length() > 0 && "".equals(fileFormat))
{
if (filename.endsWith(fileEndFormat))
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
}
}
if (log.isInfoEnabled())
{
log.info("download file is success:remotePath=" + remotePath
+ "and localPath=" + localPath + ",file size is"
+ v.size());
}
}
catch (SftpException e)
{
e.printStackTrace();
}
finally
{
// this.disconnect();
}
return filenames;
}
/**
* 下载单个文件
* @param remotePath:远程下载目录(以路径符号结束)
* @param remoteFileName:下载文件名
* @param localPath:本地保存目录(以路径符号结束)
* @param localFileName:保存文件名
* @return
*/
public boolean downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName) {
FileOutputStream fieloutput = null;
try {
// sftp.cd(remotePath);
File file = new File(localPath + localFileName);
// mkdirs(localPath + localFileName);
fieloutput = new FileOutputStream(file);
sftp.get(remotePath + remoteFileName, fieloutput);
if (log.isInfoEnabled())
{
log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
}
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (SftpException e)
{
e.printStackTrace();
}
finally
{
if (null != fieloutput)
{
try
{
fieloutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return false;
}
/**
* 下载单个文件
* @param remotePath:远程下载目录(以路径符号结束)
* @param localPath:本地保存目录(以路径符号结束)
* @return
*/
public boolean downloadFileByPath(String remotePath,String localPath) throws Exception {
String newSb = null;
FileOutputStream fieloutput = null;
String linuxFileName = null;
File file=new File("");
//ftp下载添加“upload/”
String newRemotePath="upload/"+remotePath;
try {
File linuxFilePath = new File(newRemotePath);
//获取文件名
linuxFileName=linuxFilePath.getName();
//获取文件路径
StringBuilder sb = new StringBuilder();
while (linuxFilePath.getParentFile() != null && linuxFilePath.getParentFile().getName().length() != 0) {
sb.insert(0, "/" + linuxFilePath.getParentFile().getName());
linuxFilePath = linuxFilePath.getParentFile();
}
sb.append("/");
//本地下载去掉“/upload/”
newSb=sb.toString().replace("/upload/","");
if(!isDirExist(sb.toString())){
file = new File(localPath+newSb);
file.mkdirs();
}
file = new File(localPath + newSb + linuxFileName);
fieloutput = new FileOutputStream(file);
sftp.get(newRemotePath, fieloutput);
if (log.isInfoEnabled()) {
log.info("===DownloadFile:" + linuxFileName + " success from sftp.");
}
//FileToZip.zip(localPath + newSb + linuxFileName,localPath + newSb+"sds.zip");
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
fieloutput.close();
file.delete();
} finally {
if (null != fieloutput) {
try {
fieloutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 判断目录是否存在
* @param directory
* @return
*/
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try
{
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
}
catch (Exception e)
{
if (e.getMessage().toLowerCase().equals("no such file"))
{
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 删除stfp文件
* @param directory:要删除文件所在目录
* @param deleteFile:要删除的文件
*/
public void deleteSFTP(String directory, String deleteFile) {
try
{
// sftp.cd(directory);
sftp.rm(directory + deleteFile);
if (log.isInfoEnabled())
{
log.info("delete file success from sftp.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 如果目录不存在就创建目录
* @param path
*/
public void mkdirs(String path) {
File f = new File(path);
String fs = f.getParent();
f = new File(fs);
if (!f.exists())
{
f.mkdirs();
}
}
/**
* 列出目录下的文件
*
* @param directory:要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
/**测试*/
public static void main(String[] args) {
//账号
String user = "admin";
//主机ip
String host = "10.0.14.17";
//密码
String password = "admin@123";
//服务器文件地址
String sftpPath = "upload/6201/620101/62010101/620100495/";
String sftpName = "implementFile_0_620100495_1508145243966.pdf";
String viewPath = "6213/621302/62130201/6213000191/healthyFile_0_6213000191_1514186629830.pdf";
//本地下载目录
String localPath = "D:/桌面/公安厅掌纹以及照片数据/掌纹/";
SFTPUtils sftp = null;
List<String> filePathList = new ArrayList<String>();
try {
sftp = new SFTPUtils(host, user, password);
sftp.connect();
sftp.downloadFileByPath(viewPath, localPath);
// 下载
//sftp.downloadFile(sftpPath, sftpName, localPath,"44444444.pdf");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
sftp.disconnect();
}
}
public String getHost()
{
return host;
}
public void setHost(String host)
{
this.host = host;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public int getPort()
{
return port;
}
public void setPort(int port)
{
this.port = port;
}
public ChannelSftp getSftp()
{
return sftp;
}
public void setSftp(ChannelSftp sftp)
{
this.sftp = sftp;
}
}