java实现多服务器之间的文件传输(Jsch )
jch是SSH2的纯Java实现。 允许连接到sshd服务器、端口传输、X11传输、文件传输等。
我主要在今天完成了在分布式架构下获取其他服务器文件流的功能。 顺便记下。 这还是很简单的。
我用的是1.54版,关于这个版本用的人最多。 这是地址:https://mvn repository.com/artifact/com.j craft/jsch/0.1.54
关于如何使用,看了下面的代码后,上面写着必要的注释。 实际上,您可以指定地址、端口号和帐户密码,然后通过连接进行操作。
package com.skypyb.util;
import com.jcraft.jsch.*;
import java.io.File;
import java.io.InputStream;
import java.util.Properties;
公共类jschftpfile {
私有状态通道通道通道=空值;
publicstaticstringgetpath (字符串文件路径,字符串文件名) {
String separator=File.separator; //系统分隔符
string filename=new string buffer (files path )
. append(separator )。
. append(filename ).toString );
返回文件名;
}
publicstaticinputstreamgettaskfile (字符串路径) {
inputstream download=空;
try {
Channel channel=getChannel (;
下载=下载(路径,)通道FTP (通道) );
}catch(jschexceptione ) {
e .打印堆栈跟踪(;
}catch(sftpexceptione ) {
e .打印堆栈跟踪(;
}
返回下载;
}
私有状态通道通道通道throwsjschexception
if (通道!=null (返回通道;
声明JSCH对象
JSch jSch=new JSch (;
获取Linux会话
sssionsession=jsch.getsession (' root ',' 127.0.0.1 ',22 );
//设置登录密码
session.setpassword('614 );
关闭//Key的检查
propertiessshconfig=new properties (;
sh config.put (stricthostkeychecking ),) no );
ssh config (ssh config );
连接到Linux
session.connect (;
用sftp连接
channelsFTPch=(channelsFTP ) session.openChannel ) ) sftp );
ch.connect (;
通道=通道;
返回通道;
}
publicstaticinputstreamdownload (字符串下载文件,通道FTP sftp ) throws SftpException {
inputstream inputstream=sftp.get (downloadfile );
返回输入流;
}
}