java实现在多服务器之间的文件传输(Jsch)
JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。
我主要是今天完成个分布式架构下获取其他服务器文件流的功能,顺便记一下。这个还是很简单的。
我用的是1.54版本,就这个版本用的人最多。这是地址: https://mvnrepository.com/artifact/com.jcraft/jsch/0.1.54
关于咋用,看下面代码,必要的注释都写了。其实也就是指定好地址、端口号、账户密码,连上然后就可以操作了。
package com.skypyb.util;
import com.jcraft.jsch.*;
import java.io.File;
import java.io.InputStream;
import java.util.Properties;
public class JschFTPFile {
private static Channel channel = null;
public static String getPath(String filesPath,String fileName) {
String separator = File.separator;//系统的分割符
String fileName = new StringBuffer(filesPath)
.append(separator)
.append(fileName).toString();
return fileName;
}
public static InputStream getTaskFile(String path) {
InputStream download = null;
try {
Channel channel = getChannel();
download = download(path, (ChannelSftp) channel);
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
return download;
}
private static Channel getChannel() throws JSchException {
if (channel != null) return channel;
//声明JSCH对象
JSch jSch = new JSch();
//获取一个Linux会话
Session session = jSch.getSession("root", "127.0.0.1", 22);
//设置登录密码
session.setPassword("614");
//关闭key的检验
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
//连接Linux
session.connect();
//通过sftp的方式连接
ChannelSftp ch = (ChannelSftp) session.openChannel("sftp");
ch.connect();
channel = ch;
return channel;
}
public static InputStream download(String downloadFile, ChannelSftp sftp) throws SftpException {
InputStream inputStream = sftp.get(downloadFile);
return inputStream;
}
}
