开发过程中,需求:连接到远程sftp服务器并读取其中的文件。
1.使用com.jcraft.jsch包中工具建立session连接远程sftp服务器
public static Channel connect(String username, String host, int port, String password) throws JSchException {
Session session = null;
Channel channel = null;
long start = System.currentTimeMillis();
JSch jSch = new JSch();
session = jSch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
// 设置不用检查hostKey
// 如果设置成“yes”,ssh就会自动把计算机的密匙加入“$HOME/.ssh/known_hosts”文件,
// 并且一旦计算机的密匙发生了变化,就拒绝连接
config.put("StrictHostKeyChecking", "no");
// UseDNS选项打开状态下,当客户端试图登录OpenSSH服务器时,服务器端先根据客户端的IP地址进行DNS PTR反向查询,查询出客户端的host name,然后根据查询出的客户端host name进行DNS 正向A记录查询,验证与其原始IP地址是否一致
// 这是防止客户端欺骗的一种手段,但一般我们的IP是动态的,不会有PTR记录的,打开这个选项不过是在白白浪费时间而已。
// 默认值是 “yes” ,为了提高效率减少时间消耗,则把UseDNS设置为“no”
// 用域名访问时才将此选项打开
config.put("UseDNS", "no");
session.setConfig(config);
session.connect(connectTimeOut);
session.setTimeout(readTimeOut);
channel = session.openChannel("sftp");
channel.connect();
long end = System.currentTimeMillis();
info_log.info("成功登陆sftp,登陆耗时:[" + (end - start) + "]毫秒");
return channel;
}
2.根据返回的channel列举服务器上文件,并依次按行读取文件内容
ChannelSftp channel = null;
try {
//连接远程sftp
channel = (ChannelSftp) FtpUtil.connect(ftpUserName, ftpHost, ftpPort, ftpPasswd);
Vector<ChannelSftp.LsEntry> ftpFiles = channel.ls(ftpRootDir);//列举指定目录中文件
if (ftpFiles != null && ftpFiles.size() > 0) {
for (LsEntry lsEntry : ftpFiles) {
String filename = lsEntry.getFilename();
BufferedReader bufferedReader = null;
try {
channel.cd(ftpRootDir);//进入指定目录操作
InputStream inputStream = channel.get(filename);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String tempString = null;
while ((tempString = bufferedReader.readLine()) != null) {
//....数据处理
}
} catch (Exception e) {
} finally {
try {
if (bufferedReader != null)
bufferedReader.close();//关闭流
} catch (IOException e) {
log.error("Close BufferedReader error:", e);
}
}
}
}
} catch (Exception e) {
} finally {
//记得关闭连接
if (channel != null) {
channel.quit();
channel.disconnect();
try {
if (channel.getSession() != null)
channel.getSession().disconnect();
} catch (JSchException e) {
log.error("channel getSession error:", e);
}
}