package cn.aofeng;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import cn.aofeng.dto.SftpConnectInfo;
import cn.aofeng.util.ConsoleProgressBar;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.SftpProgressMonitor;
* 使用SFTP从远程主机下载文件。
*
* @author 傲风 <aofengblog@163.com>
*/
public class SftpDownloader {
private final static Logger logger = Logger.getLogger(SftpDownloader.class);
* 使用SFTP从远程主机下载文件。
*
* @param connectInfo SFTP连接信息
* @param localPath 本地文件路径
* @param remotePath 远程文件路径
*/
public void download(SftpConnectInfo connectInfo, String localPath, final String remotePath) {
JSch jsch = new JSch();
Session session = null;
ChannelSftp channel = null;
OutputStream outs = null;
try {
session = jsch.getSession(connectInfo.getUsername(), connectInfo.getHost(), connectInfo.getPort());
session.setPassword(connectInfo.getPassword());
Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
session.setConfig(props);
session.connect(5000);
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect(5000);
outs = new BufferedOutputStream(
new FileOutputStream(
new File(localPath)));
channel.get(remotePath, outs, new SftpProgressMonitor() {
ConsoleProgressBar progress = null;
private long current = 0;
@Override
public void init(int op, String src, String dest, long max) {
progress = new ConsoleProgressBar(0, max, 50);
}
@Override
public void end() {
if (logger.isInfoEnabled()) {
logger.debug( String.format("download file:%s complete", remotePath) );
}
}
@Override
public boolean count(long count) {
current += count;
progress.show(current);
return true;
}
});
} catch (JSchException e) {
logger.error( String.format("connect remote host[%s:%d] occurs error", connectInfo.getHost(), connectInfo.getPort()), e);
} catch (SftpException e) {
logger.error( String.format("get remote file:%s occurs error", remotePath), e);
} catch (FileNotFoundException e) {
logger.error( String.format("can not find local file:%s", localPath), e);
} finally {
IOUtils.closeQuietly(outs);
if (null != channel) {
channel.disconnect();
}
if (null != session) {
session.disconnect();
}
}
}
}