使用JSch访问服务端日志

有些操作,需要短信验证码,就要每次到服务端查看日志。有些同事不知道如何查看,就写了页面方便大家调用查看服务端日志。

1.Service层

1.1Service接口

package com.csj2018.o2o.service;

import java.io.IOException;

import com.jcraft.jsch.JSchException;

public interface WangLog {
    String[] getMessage(String command) throws JSchException,IOException;
}

1.2.Service实现类

package com.csj2018.o2o.service.impl;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.stereotype.Service;

import com.csj2018.o2o.service.WangdaLog;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
@Service
public class WangLogImpl implements WangLog{
    private String host = "IP地址";
    private int port = 22;
    private String username = "用户名";
    private String password = "密码";
    @Override
    public String[] getMessage(String command) throws IOException {
        StringBuilder sb = new StringBuilder();
        // 创建JSch
        JSch jSch = new JSch();
        // 获取session
        Session session;
        try {
            session = jSch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");

            // 启动连接
            session.connect();
            ChannelExec exec = (ChannelExec)session.openChannel("exec");
            exec.setCommand(command);
            exec.setInputStream(null);
            exec.setErrStream(System.err);
            InputStream in = exec.getInputStream();
            exec.connect();

            byte[] tmp = new byte[1024];
            while(true){
                while(in.available() >0){
                    int i = in.read(tmp,0,1024);
                    if(i<0){
                        break;
                    }
                    sb.append(new String(tmp,0,1024));
                }
                
                if(exec.isClosed()){
                    if(in.available()>0){
                        continue;
                    }
                    System.out.println("exit_statux:"+exec.getExitStatus());
                    break;
                }
                try{Thread.sleep(1000);}catch(Exception ee){}
            }

            exec.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return sb.toString().split("\n");
    }
    
}

1.3测试Service层

package com.csj2018.o2o.service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.csj2018.o2o.BaseTest;
import com.jcraft.jsch.JSchException;

public class WangLogTest extends BaseTest{
    @Autowired
    private WangLog wangLog;
    @Test
    public void test() throws JSchException, IOException {
        String[] logs = wangLog.getMessage("cd /data/logs/message-service/; grep value message-service.log |tail -n 10;");
        for(String s:logs) {
            System.out.println(s);
        }
    }
}

2.controller层

package com.csj2018.o2o.web.shopadmin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csj2018.o2o.entity.Area;
import com.csj2018.o2o.entity.Param;
import com.csj2018.o2o.service.AreaService;
import com.csj2018.o2o.service.WangLog;
import com.csj2018.o2o.service.YYGHParamService;
import com.csj2018.o2o.util.HttpServletRequestUtil;
import com.csj2018.o2o.web.superadmin.AreaController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcraft.jsch.JSchException;

@Controller
@RequestMapping("/superadmin")
public class Getparam {
    Logger logger = LoggerFactory.getLogger(AreaController.class);
    @Autowired
    private WangLog wangLog;
    @RequestMapping(value="/wangmessage", method=RequestMethod.POST)
    @ResponseBody
    private Map<String,Object> getMessageLog(@RequestBody Map<String,String> request){
        Map<String, Object> modelMap = new HashMap<>();
        try {
            String command = request.get("command");
            System.out.println(command);
            String[] logs= wangdaLog.getMessage(command);
            logger.info("日志:"+Arrays.toString(logs));
            modelMap.put("logs", logs);
            modelMap.put("success", true);
        }catch (JSchException e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
        }catch (IOException e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.toString());
        }
        return modelMap;
        
    }
}

3.前端

3.1 webapp/wang.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SUI Mobile Demo</title>
<meta name="description"
    content="MSUI: Build mobile apps with simple HTML, CSS, and JS components.">
<meta name="author" content="查看外部浏览器日志">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">

<!-- Google Web Fonts -->

<link rel="stylesheet"
    href="//g.alicdn.com/msui/sm/0.6.2/css/sm.min.css">
<link rel="stylesheet"
    href="//g.alicdn.com/msui/sm/0.6.2/css/sm-extend.min.css">

<script>
    //ga
</script>
<script>
    var _hmt = _hmt || [];
    (function() {
        var hm = document.createElement("script");
        hm.src = "//hm.baidu.com/hm.js?ba76f8230db5f616edc89ce066670710";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

</head>
<body>
    <div class="page-group">
        <div id="page-label-input" class="page">
            <header class="bar bar-nav">
                <h1 class="title">log查看</h1>
            </header>
            <div class="content">
                <div class="list-block">
                    <ul>
                        <!-- 字符串 -->
                        <li>
                            <div class="item-content">
                                <div class="item-inner">
                                    <div class="item-title label">log查看</div>
                                    <div class="item-input">
                                        <textarea id="command" rows="10" cols="50" placeholder='请输入命令。命令之间以";"间隔'></textarea>
                                    </div>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
                
                <div class="content-block">
                    <div class="row">
                        <div class="col-35" style="padding-left:100px;">
                            <!-- android解密 -->
                            <a  href="#" class="button button-big button-fill button-success" id="getlog">获取日志</a>
                        </div>
                    </div>
                </div>
                <div class="item-content">
                    <ul>
                        <li>
                            <text>结果字符串</text>
                            <div class="item-inner" id="result" style="word-wrap:break-word;word-break:break-all;padding-left: 5px;padding-right: 5px;width: wrap-content;">
                            </div>
                        </li>
                    </ul>
                </div>              
            </div>
            </div>
        </div>

    </div>
    <script type='text/javascript'
        src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script>
    <script type='text/javascript'
        src='//g.alicdn.com/msui/sm/0.6.2/js/sm.min.js' charset='utf-8'></script>
    <script type='text/javascript'
        src='//g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script>
    <script type='text/javascript'
        src='./resources/js/shop/wang.js' charset="utf-8"></script>

</body>
</html>

3.2 webapp/resources/js/shop/wang.js

/**
 * 
 */
/**
 * 
 */
$(function(){
    var logUrl = '/o2o/superadmin/wangmessage';
    getShopInitInfo();
    function getShopInitInfo(){
    
    $('#getlog').click(function(){
        var formData = {command:$('#command').val()};
        $.ajax({
            url:logUrl,
            type:'POST',
            data:JSON.stringify(formData),
            contentType:'application/json',
            processData:false,
            cache:false,
            success:function(data){
                if(data.success){
                    $.toast("提交成功!");
                    //获取响应内容
//                  alert(JSON.stringify(data.decrypt));
                    var logs = data.logs;
                    var temp = '<ul>';
                    for(i=0;i<logs.length;i++){
                        temp += '<li><text>'+logs[i]+'</text></li>';
                    }
                    temp +='</ul>';
//                  $.toast(data.logs);
                    $('#result').html(temp);
                    //填充
                }else{
                    $.toast("提交失败:"+data.errMsg);
                }
            }
        });
    });
    
    }
})

3.3 验证

参考博客:
https://www.cnblogs.com/xiaoliu66007/p/11084208.html
https://www.cnblogs.com/jing1617/p/7132100.html

猜你喜欢

转载自www.cnblogs.com/csj2018/p/12517265.html