背景:有一个需求,需要从远程服务器,拉取文件到本地解析,然后存入es中。
2种方式文件下载,scp,sftp文件下载:
1、scp方式文件下载
2、sftp方式文件下载
sftp权限更容易获取一些,如果不知道使用哪种方式,推荐sftp
1、scp方式文件下载
引用jar包:
<!--ssh-->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
相关代码:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 下载远程文件 到服务器本地
*/
@Slf4j
@Component
public class ScpSynFile {
@Value("${synfile.ip}")
private String IP;
@Value("${synfile.port}")
private int PORT;
@Value("${synfile.user}")
private String USER;
@Value("${synfile.pwd}")
private String PWD;
/**
* scp远程下载服务器文件
*
* @param sourceFilePath 远程文件路径
* @param targetFilePath 本地文件路径
* @param targetFileName 本地文件名称
* @return
*/
public boolean downloadFile(String sourceFilePath, String targetFilePath, String targetFileName) {
boolean bool = false;
FileOutputStream fos = null;
try {
log.info("==============下载远程文件 开始 :" + sourceFilePath);
// 创建连接
Connection conn = getConn();
SCPClient scpClient = conn.createSCPClient();
SCPInputStream scpis = scpClient.get(sourceFilePath);
// 判断指定目录是否存在,不存在则先创建目录
File file = new File(targetFilePath);
if (!file.exists()) {
file.mkdirs();
}
// 下载文件
fos = new FileOutputStream(targetFilePath + targetFileName);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = scpis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
bool = true;
log.info("==============下载远程文件 结束 :" + sourceFilePath);
} catch (Exception e) {
log.error("==============下载远程文件 失败 :", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioException) {
log.error("==============下载远程文件关闭文件输入流 失败 :", ioException);
}
}
}
return bool;
}
/**
* 连接远程主机
*
* @return
*/
public Connection getConn() {
Connection conn = new Connection(IP, PORT);
if (conn.isAuthenticationComplete()) {
return conn;
}
try {
log.info("========================开始连接远程主机");
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(USER, PWD);
if (!isAuthenticated) {
throw new Exception("authentication failed!");
}
return conn;
} catch (Exception e) {
log.error("========================主机连接失败 Connect error:", e);
}
return null;
}
}
2、sftp方式文件下载
引用jar包:
<!--sftp-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
相关代码:
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 下载远程文件 到服务器本地
*/
@Slf4j
@Component
public class SftpSynFile {
@Value("${synfile.ip}")
private String IP;
@Value("${synfile.port}")
private int PORT;
@Value("${synfile.user}")
private String USER;
@Value("${synfile.pwd}")
private String PWD;
/**
* Sftp下载单个文件
*
* @param sourceFilePath 远程文件路径
* @param targetFilePath 本地文件路径
* @param targetFileName 本地文件名称
* @return
*/
public boolean downloadFile(String sourceFilePath, String targetFilePath, String targetFileName) {
FileOutputStream fieloutput = null;
ChannelSftp sftp = null;
try {
// 创建连接
sftp = getConn();
// 判断指定目录是否存在,不存在则先创建目录
File file = new File(targetFilePath);
if (!file.exists()) {
file.mkdirs();
}
// 下载文件
fieloutput = new FileOutputStream(targetFilePath + targetFileName);
log.info("========================sftp下载单个文件开始:" + sourceFilePath);
sftp.get(sourceFilePath, fieloutput);
log.info("========================sftp下载单个文件结束:" + sourceFilePath);
return true;
} catch (Exception e) {
log.error("========================sftp下载单个文件失败:", e);
} finally {
if (null != fieloutput) {
try {
fieloutput.close();
} catch (IOException e) {
log.error("========================FileOutputStream关闭失败:", e);
}
}
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
}
return false;
}
/**
* sftp连接远程主机
*
* @return
*/
public ChannelSftp getConn() {
try {
log.info("========================sftp连接远程主机开始");
JSch jsch = new JSch();
jsch.getSession(USER, IP, PORT);
com.jcraft.jsch.Session sshSession = jsch.getSession(USER, IP, PORT);
sshSession.setPassword(PWD);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
log.info("========================sftp连接远程主机结束");
return (ChannelSftp) channel;
} catch (Exception e) {
log.error("========================sftp连接远程主机失败 Connect error:", e);
}
return null;
}
}