在日常开发中,遇见远程下载的需求,具体是在windows环境连接linux环境进行远程下载文件。下面是选用jsch组件进行的实现。
JSch(Java Secure Channel)是一个ssh2的java实现,允许连接到一个ssh服务器(即典型的xshell连接方式),并且可以使用端口转发,文件传输等。使用SFTP协议。
SFTP(Secure File Transfer Protocol)安全文件传送协议,可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式,但是传输效率比普通的FTP要低。
public class SftpUtils {
private static final Logger log = LoggerFactory.getLogger(SftpUtils.class);
private String host;
private String username;
private String password;
private int port = 22;
private int timeOut = 6000;
private ChannelSftp channelSftp = null;
private Session sshSession = null;
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();
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.setTimeout(timeOut);
sshSession.connect();
channelSftp = (ChannelSftp) sshSession.openChannel("sftp");
channelSftp.connect();
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void disconnect() {
if (this.channelSftp != null) {
if (this.channelSftp.isConnected()) {
this.channelSftp.disconnect();
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
}
}
}
/**
* 批量下载文件
* @param remotePath:远程下载目录
* @param localPath:本地保存目录
* @return
*/
public List<String> batchDownLoadFile(String remotePath, String localPath) {
return batchDownLoadFile(remotePath, localPath, null, null, false);
}
/**
* 批量下载文件
* @param remotePath:远程下载目录
* @param localPath:本地保存目录
* @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<>();
try {

本文介绍如何利用JSch库在Windows环境中通过SSH连接Linux服务器,实现SFTP协议下的文件批量下载、上传功能,包括连接配置、通道操作和示例代码演示。
最低0.47元/天 解锁文章
1256

被折叠的 条评论
为什么被折叠?



