demon 8 éve
szülő
commit
56ff66043a

+ 3 - 2
hos-arbiter/src/main/java/com/yihu/hos/arbiter/routers/LinuxShellRouter.java

@ -12,6 +12,7 @@ import org.springframework.stereotype.Component;
import javax.jms.ConnectionFactory;
/**
 * 中心shell命令消息
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/5.
@ -29,11 +30,11 @@ public class LinuxShellRouter extends RouteBuilder {
                activemqConfiguration.getUser(), activemqConfiguration.getPassword(), activemqConfiguration.getBrokerURL());
        // Note we can explicit name the component
        context.addComponent("service.shell.event", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
        from(ServiceFlowConstant.SHELL_EVENT_ENDPOINT)
        from(ServiceFlowConstant.SHELL_EVENT_SERVICE)
                .choice()
                .when(header("tenant").isNotNull()).to("bean:linuxShellService?method=proxy")
                .when(header("event").isEqualTo(ServiceFlowConstant.ARBITER_SHELL_SEND)).to("bean:linuxShellService?method=sendShell")
                .when(header("event").isEqualTo(ServiceFlowConstant.ARBITER_SHELL_ACEPT)).to("bean:linuxShellService?method=shellBack")
//                .when(header("event").isEqualTo(ServiceFlowConstant.ARBITER_SHELL_ACEPT)).to("bean:linuxShellService?method=shellBack")
                .endChoice();
    }
}

+ 2 - 4
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/LinuxShellService.java

@ -49,7 +49,7 @@ public class LinuxShellService {
        try {
            //TODO 设置shell发起用户
            Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SHELL_ARBITER + "@" + header.get("tenant"));
            Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SHELL_REQUEST + "@" + header.get("tenant"));
            producer.createMQ();    //确定为创建消息队列需要显示调用
            Message message = new Message();
            message.setHead("event", header.get("event"));
@ -82,7 +82,7 @@ public class LinuxShellService {
                    System.out.println("发送shell请求到broker成功!!!");
                    //TODO shell执行成功,见执行结果返回到中心显示。
                    ServiceShell serviceShell = objectMapper.readValue(msg,ServiceShell.class);
                    Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SHELL_ADMIN + "@" + serviceShell.getTenant());
                    Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SHELL_RESPONSE + "@" + serviceShell.getTenant());
                    producer.createMQ();    //确定为创建消息队列需要显示调用
                    Message message = new Message();
                    message.setHead("event", serviceShell.getType());
@ -90,7 +90,6 @@ public class LinuxShellService {
                    message.setMethod("POST");
                    message.setBody(result);
                    message = producer.sendSync(message);
                    System.out.println("发送到中心zubs的shell结果!"+message);
                }
            }
        } catch (Exception e) {
@ -110,7 +109,6 @@ public class LinuxShellService {
                HTTPResponse response = HttpClientKit.post(brokerServer.getURL() + path, msg);
                if (response.getStatusCode() == 200) {
                    String body = response.getBody();
                    System.out.println(body);
                    return body;
                }

+ 2 - 2
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ShellService.java

@ -36,7 +36,7 @@ public class ShellService {
        header.put("event", message.getHead("event"));
        ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
        producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.SHELL_EVENT_ENDPOINT, message.getBodyString(), header);
        producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.SHELL_EVENT_SERVICE, message.getBodyString(), header);
    }
    public void start() {
@ -45,7 +45,7 @@ public class ShellService {
            return;
        }
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_ARBITER + "@" + configuration.getTenant());
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_REQUEST + "@" + configuration.getTenant());
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {

+ 55 - 5
hos-broker/src/main/java/com/yihu/hos/broker/common/shell/SSHLinuxTool.java

@ -1,14 +1,12 @@
package com.yihu.hos.broker.common.shell;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
/**
 * ssh 链接操作测试类
@ -93,7 +91,7 @@ public class SSHLinuxTool {
            OutputStream outstream = channel.getOutputStream();
            //发送需要执行的SHELL命令,需要用\n结尾,表示回车
            String shellCommand = command + " \n";
            String shellCommand = command;
            outstream.write(shellCommand.getBytes());
            outstream.flush();
@ -125,4 +123,56 @@ public class SSHLinuxTool {
        return null;
    }
    /**
     *
     * @param session       ssh会话
     * @param inputStream   文件流
     * @param targetDir     上传的目标文件夹
     * @param targetFileName    上传的目标文件名
     * @throws Exception
     */
    public  void sshSftp(Session session,InputStream inputStream, String targetDir,String targetFileName) throws Exception{
        Channel channel = null;
        //如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            sftp.cd(targetDir);
            //列出服务器指定的文件列表
            Vector v = sftp.ls("*.txt");
            for(int i=0;i<v.size();i++){
                System.out.println(v.get(i));
            }
            //以下代码实现从本地上传一个文件到服务器,如果要实现下载,对换以下流就可以了
            OutputStream outstream = sftp.put(targetFileName);
            byte b[] = new byte[1024];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                outstream.write(b, 0, n);
            }
            outstream.flush();
            outstream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            channel.disconnect();
        }
    }
}

+ 3 - 3
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java

@ -42,14 +42,14 @@ public interface ServiceFlowConstant {
    // shell 请求命令,对列名称
    String SHELL_EVENT_QUEUE = "configuration.service.shell";
    String SHELL_EVENT_ENDPOINT = "service.shell.event:queue:configuration.service.shell";
    String SHELL_EVENT_SERVICE = "service.shell.event:queue:configuration.service.shell";
    //Arbiter shell
    String ARBITER_SHELL_SEND = "arbiterShellSend"; //shell 命令执行消息
    String ARBITER_SHELL_ACEPT = "arbiterShellAcept"; //shell 执行结果消息
    //arbiter 发送shell命令 消息队列
    String SHELL_ARBITER = "shell_arbiter";
    String SHELL_REQUEST = "shell_request";
    // hos-admin 接收shell执行结果
    String SHELL_ADMIN = "shell_admin";
    String SHELL_RESPONSE = "shell_response";
}

+ 2 - 0
src/main/java/com/yihu/hos/common/constants/ContextAttributes.java

@ -10,5 +10,7 @@ public interface ContextAttributes {
    String TENANT_SESSION = "tenantSession";
    String GLOBAL_DB = "global_db";//平台管理中心库
    String SHELL_RESPONSE = "shell_repsonse";
}

+ 26 - 36
src/main/java/com/yihu/hos/remoteManage/controller/RemoteShellController.java

@ -1,6 +1,9 @@
package com.yihu.hos.remoteManage.controller;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.interceptor.LocalContext;
import com.yihu.hos.remoteManage.service.RemoteShellService;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
@ -35,13 +38,13 @@ public class RemoteShellController extends BaseController {
     */
    @RequestMapping("/initial")
    public String appInitial(Model model) {
        model.addAttribute("contentPage", "shell/shell");
        model.addAttribute("contentPage", "/monitor/shell/shell");
        return "partView";
    }
    @RequestMapping(value = "/shell", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @RequestMapping(value = "/sendShell", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String shellTest(
    public Result sendShell(
            @ApiParam(name = "command", value = "shell命令")
            @RequestParam(value = "command", required = false) String command,
//            @ApiParam(name = "tenant", value = "租户名称")
@ -51,47 +54,34 @@ public class RemoteShellController extends BaseController {
        String result = "";
        try {
            //TODO 发送shell命令 消息
            System.out.println("发送shell请求==================");
            System.out.println("发送shell请求:"+command);
            remoteShellService.sendShell(command, disCon);
            System.out.println("结果1:" + result);
            //TODO 接收shell命令执行结果 消息
            remoteShellService.start();
            result=remoteShellService.backResult;
            System.out.println("接口返回结果:"+result);
            return Result.success("shell请求发送成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
        return Result.error("shell请求发送失败!");
    }
//
//    //连接操作shell测试
//    @RequestMapping(value = "/shell", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
//    @ResponseBody
//    public String shellTest(String cmd, String disCon) {
//        String result = "";
//        try {
//            if (session==null){
//                session = sshLinuxTool.getsessionConn();
//            }
//            if ("false".equals(disCon)) {
//                //保持通道连接
//                System.out.println("循环开始1111111==================");
//                result = sshLinuxTool.sshShell(session, cmd, false);
//                System.out.println("结果:"+result);
//            } else {
//                //断开通道连接,会话
//                System.out.println("循环开始2222222222==================");
//                result = sshLinuxTool.sshShell(session, cmd, true);
//                session = null;
//                System.out.println("结果:"+result);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return result;
//    }
    @RequestMapping(value = "/getShellBack", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getShellBack() {
        //TODO  切换用户的时候记得清除该值
        String result = "";
        try {
            //TODO 如何去除等待时间,目前添加sleep是因为需要等待zbus回调方法的返回结果;
            Thread.sleep(3000);
            result = LocalContext.getContext().getAttachment(ContextAttributes.SHELL_RESPONSE);
            System.out.println("接口返回结果:"+result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}

+ 5 - 8
src/main/java/com/yihu/hos/remoteManage/service/RemoteShellService.java

@ -31,7 +31,6 @@ public class RemoteShellService {
    private ServiceShellEventService serviceShellEventService;
    private ZbusBroker zbusBroker;
    private Consumer consumer;
    public static String backResult;
    /**
     * 发送shell命令消息
@ -59,9 +58,10 @@ public class RemoteShellService {
    public void proxy(Message message, Consumer consumer) {
        String bodyString = message.getBodyString();
        this.backResult=bodyString;
        LocalContext.getContext().setAttachment(ContextAttributes.SHELL_RESPONSE,bodyString);
        System.out.println("回调返回:" + bodyString);
    }
    public void start() {
@ -74,14 +74,13 @@ public class RemoteShellService {
        if (attachment==null){
            return;
        }
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_ADMIN + "@" + attachment);
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_RESPONSE + "@" + attachment);
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
@ -96,6 +95,4 @@ public class RemoteShellService {
        super.finalize();
    }
}

+ 2 - 2
src/main/webapp/WEB-INF/ehr/jsp/common/indexJs.jsp

@ -88,6 +88,8 @@
                {id: 52, pid: 5, text: '服务监控', url: '${contextRoot}/monitor/service/initial'},
                {id: 53, pid: 5, text: '任务跟踪', url: '${contextRoot}/datacollect/trackJob', targetType: '1'},
                {id: 54, pid: 5, text: '任务补采', url: '${contextRoot}/datacollect/repeatDatacollect'},
                {id: 55, pid: 5, text: '远程管理', url: '${contextRoot}/shell/initial'},
                //资源管理
                {id: 3, text: '资源服务', icon: '${staticRoot}/images/index/menu4_icon.png'},
                {id: 31, pid: 3, text: '资源注册', url: '${contextRoot}/resource/resource/initial'},
@ -124,8 +126,6 @@
            menu =  menu.concat(menu_1);
            debugger
            me.menuTree = $('#ulTree').ligerTree({
                data: menu,
                idFieldName: 'id',

+ 31 - 0
src/main/webapp/WEB-INF/ehr/jsp/monitor/shell/shell.jsp

@ -0,0 +1,31 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!--######用户管理页面Title设置######-->
<style >
    #main_text{
        width: 60%;
        background: black;
        color: white;
        height: 500px;
        font-size: 18px;
    }
</style>
<!-- ####### 页面部分 ####### -->
<div class="m-content">
    <!-- ####### 查询条件部分 ####### -->
    <div class="m-form-inline">
        <div class="m-form-group">
            <div class="m-form-control left" >
                <label>输入shell命令:</label>
            </div>
        </div>
    </div>
    <!--######菜单信息表######-->
    <div id="div_grid">
        <textarea id="main_text"></textarea>
    </div>
</div>

+ 101 - 0
src/main/webapp/WEB-INF/ehr/jsp/monitor/shell/shellJs.jsp

@ -0,0 +1,101 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<script>
    /* *************************** 模块初始化 ***************************** */
    var shell = {
        grid: null,
        dialog: null,
        init: function () {
            this.bindEvents();
            this.initForm();
        },
        initForm: function () {
            var me = this;
            $('.m-retrieve-area').show();
        },
        bindEvents: function () {
            var me = this;
            $(".l-text").css("display","inline-block");
            $(".l-text-wrapper").css("display","inline-block");
            $("#main_text").keyup(function (e) {
                if (e.keyCode == 13) {
                    var command = $("#main_text").val();
                    var arr=command.split("\r\n");
                    var currentCommand = arr[0].split("]#");
                   me.sendShell(currentCommand[1]);
                }
            });
        },
        anthorize: function (id) {
        },
        sendShell:function(command){
            $.ajax({ //ajax处理
                type: "GET",
                url : "${contextRoot}/shell/sendShell",
                dataType : "json",
                data:{command:command,disCon:false},
                cache:false,
                success :function(data){
                    if(data.successFlg) {
                        var flg = data.successFlg;
                        if(flg){
                            debugger
                            shell.getShellBack();
                        }else{
                            alert("shell请求命令失败!");
                        }
                    }
                    else{
                        $.ligerDialog.error(data.message);
                    }
                },
                error :function(data){
                    $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
                }
            });
        },
        getShellBack:function(){
            $.ajax({ //ajax 获取shell执行结果
                type: "GET",
                url : "${contextRoot}/shell/getShellBack",
                dataType : "json",
                data:{},
                cache:false,
                success :function(data){
                    if(data.successFlg) {
                        var flg = data.successFlg;
                        if(flg){
                            $("#main_text").val(data.message);
                        }else{
                            alert("shell请求命令失败!");
                        }
                    }
                    else{
                        $.ligerDialog.error(data.message);
                    }
                },
                error :function(data){
                    $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
                }
            });
        },
        //弹窗返回
        dialogSuccess: function (message) {
            $.ligerDialog.success(message);
            shell.reloadGrid();
            shell.dialog.close();
        }
    };
    $(function () {
        shell.init();
        shell.sendShell("\n");
    });
</script>