sftp链接服务器的工具类
package com.sxiic.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
* 参考文档JSch
* http://www.cnblogs.com/chen1987lei/archive/2010/11/26/1888384.html
* http://jerval.iteye.com/blog/2150030
*/
public class SFtpClientUtil {
private JSch jsch = null;
private String host;//服务器地址:192.168.1.182
private int port;//端口:22
private String username;//登录名:root
private String password;//密码:goojia123456
ChannelSftp sftp = null;
Channel channel = null;
Session sshSession = null;
public ChannelSftp getSftp() {
return sftp;
}
public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
public SFtpClientUtil(String host, int port, String username,
String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}
public static void main(String[] args) {
//connect("192.168.1.182", 22, "root", "goojia123456");
SFtpClientUtil s = new SFtpClientUtil("192.168.1.182", 22, "root", "goojia123456");
s.connect();
s.closeConnect();
}
/**
* 链接到服务器
*/
public boolean connect() {
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 链接到服务器
*/
public void closeConnect() {
closeChannel(sftp);
closeChannel(channel);
closeSession(sshSession);
}
public static void closeChannel(Channel channel) {
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
}
}
}
public static void closeSession(Session session) {
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
//是否存在文件夹
public boolean ifdirectory(String directory){
try{
sftp.cd(directory);
return true;
}catch(SftpException sException){
if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){
return false;
}
return false;
}
}
}
spring mvc调用,将服务器日志文件的内容展示出来
package com.sxiic.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.sxiic.util.SFtpClientUtil;
//http://lavasoft.blog.51cto.com/62575/100386/
//http://jerval.iteye.com/blog/2150030
//http://www.cnblogs.com/chen1987lei/archive/2010/11/26/1888384.html
@Controller
@RequestMapping("/sftpclient")
public class SFtpClientController extends BaseController{
/**
* 后台用户列表
*/
@RequestMapping(value="/testsftp/**",method= RequestMethod.GET)
public String testFtp(HttpServletRequest request,Model model){
//connect("192.168.1.182", 22, "root", "goojia123456","/home","3-8.log");
String url = request.getRequestURI().substring(request.getContextPath().length()+"/sftpclient/testsftp".length(),request.getRequestURI().length());
String logname = "";
if(url.indexOf('.') != -1){
logname = url.substring(url.lastIndexOf("/")+1, url.length());
url = url.substring(0, url.lastIndexOf("/"));
}
SFtpClientUtil s = new SFtpClientUtil("192.168.1.182", 22, "root", "goojia123456");
ChannelSftp sftp = null;
String dir = "/home";
dir+=url;
List<String> dirList = new ArrayList<String>();
List<String> fileList = new ArrayList<String>();
List<String> contentlist = new ArrayList<String>();
List<String> fileanddirList = new ArrayList<String>();
try {
if (s.connect()) {
sftp = s.getSftp();
if(StringUtils.isBlank(logname)){
//返回的是目录
Vector<LsEntry> listFiles= sftp.ls(dir);
for (LsEntry entry:listFiles) {
if(entry.getFilename().indexOf('.') == -1){
System.out.println(entry.getFilename());
dirList.add(entry.getFilename());
}else{
System.out.println(entry.getFilename());
fileList.add(entry.getFilename());
}
if(entry.getFilename().equals(".") || entry.getFilename().equals("..")){
}else{
fileanddirList.add(entry.getFilename());
}
}
//return 目录;
model.addAttribute("resul", 1);
model.addAttribute("fdlist", fileanddirList);
model.addAttribute("url", url);
return "sftp_log_list";
}else{
sftp.cd(dir);
//返回的是log内容
InputStream out= sftp.get(logname);
String content = readInputStream(out);
String[] contentarray = content.split("\\|\\|");
for(int i=0;i<contentarray.length;i++){
//System.out.println(contentarray[i]);
contentlist.add(contentarray[i]);
}
//return 文本内容;
model.addAttribute("resul", 2);
model.addAttribute("contentlist", contentlist);
System.out.println("数据查询完毕!");
return "sftp_log_list";
}
}
} catch (Exception e) {
e.printStackTrace();
model.addAttribute("resul", 3);
model.addAttribute("falireson", e.getMessage());
return "sftp_log_list";
}finally{
s.closeConnect();
}
model.addAttribute("resul", 4);
model.addAttribute("falireson", "直接执行finally");
return "sftp_log_list";
}
public static String readInputStream(InputStream inputStream) {
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
//将文本打印到控制台
sb.append(line);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
reader.close();
//bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
jsp页面展示
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>三弦转换后台</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="resources/css/bg.css" rel="stylesheet" type="text/css" />
<link href="resources/css/base.css" rel="stylesheet" type="text/css" />
<link href="resources/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="resources/js/jquery-1.5.1.min.js"></script>
<script src="resources/js/colResizable-1.3.min.js"></script>
<script type="text/javascript" src="resources/js/My97DatePicker/WdatePicker.js"></script>
<link href="resources/js/jquery-jbox/2.3/Skins/Bootstrap/jbox.css" rel="stylesheet" />
<script src="resources/js/jquery-jbox/2.3/jquery.jBox-2.3.min.js" type="text/javascript"></script>
<script src="resources/js/jquery-jbox/2.3/i18n/jquery.jBox-zh-CN.min.js" type="text/javascript"></script>
</head>
<body class="h_body">
<div id="main-box">
<div class="main-content">
<!-- 面包屑 -->
<div id="bread">平台 > 日志管理 > 日志列表 <i class="bread-icon"></i></div>
<table id="searchTable">
<thead>
<tr>
<th width="50%">日志</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${resul==1}">
<c:forEach items="${fdlist}" var="fd">
<tr>
<td><a href="sftpclient/testsftp${url}/${fd}">${fd}</a></td>
</tr>
</c:forEach>
</c:when>
<c:when test="${resul==2}">
<c:forEach items="${contentlist}" var="content">
<tr>
<td>${content}</td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr>
<td>${resul}+"--"${falireson}</td>
</tr>
</c:otherwise>
</c:choose>
</tbody>
</table>
</div>
</div>
<script type="text/javascript" >
</script>
</body>
</html>