public class FileUploader {
private static Logger logger = LoggerFactory.getLogger(FileUploader.class);
private ChannelSftp sftp = null;
private Session sshSession = null;
private Channel channel = null;
public ChannelSftp getSftp() {
return sftp;
}
/**
* 建立sftp连接
*/
public void getConnection(String hostIp, int hostPort, String userName, String passWord) {
try {
JSch jsch = new JSch();
sshSession = jsch.getSession(userName, hostIp, hostPort);
sshSession.setPassword(passWord);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
channel = sshSession.openChannel("sftp");
channel.connect();
logger.info("sftp已经连接到:" + hostIp + ":" + hostPort);
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
logger.error("get connection error:", e);
logger.info("sftp未连接到:" + hostIp + ":" + hostPort);
}
}
public void closeConnection() {
if (sshSession != null) {
sshSession.disconnect();
logger.info("sftp session关闭");
}
if (sftp != null) {
sftp.disconnect();
logger.info("sftp connection关闭");
}
}
public boolean fileDownload(String sourceFilePath, String localFilePath) throws Exception {
boolean fileExistFlag = false;
try {
sftp.get(sourceFilePath, localFilePath);
fileExistFlag = true;
} catch (Exception ignored) {
logger.warn("文件在sftp服务器上不存在,{}", sourceFilePath);
}
return fileExistFlag;
}
引用JAR包:JSCH–>http://mvnrepository.com/artifact/com.jcraft/jsch