Преглед на файлове

Merge branch 'master' of http://192.168.1.220:10080/esb/esb

Airhead преди 8 години
родител
ревизия
6a97a00087

+ 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();
    }
}

+ 12 - 6
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/LinuxShellService.java

@ -35,6 +35,9 @@ public class LinuxShellService {
    @Autowired
    private ObjectMapper objectMapper;
    private ShellService shellService;
    /**
     * SAAS化的管理端过来的消息会被proxy进行中转,之后发送到终端的Arbiter对Broker进行实际的控制。
     *
@ -49,7 +52,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"));
@ -58,6 +61,7 @@ public class LinuxShellService {
            message.setBody(msg);
            message = producer.sendSync(message);
            logger.debug(message);
            shellService.start();
//            System.out.println("test");
        } catch (IOException | InterruptedException e) {
            logger.error(e.getMessage());
@ -79,10 +83,10 @@ public class LinuxShellService {
                    logger.error("sendMessage to broker server failed, broker:" + broker.getURL() + ", msg:" + msg);
                    continue;
                }else {
                    System.out.println("发送shell请求到broker成功!!!");
                    //TODO shell执行成功,见执行结果返回到中心显示。
                    logger.debug("发送shell请求到broker成功");
                    // shell执行成功,见执行结果返回到中心zbus显示。
                    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 +94,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 +113,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;
                }
@ -153,4 +155,8 @@ public class LinuxShellService {
        this.zbusBroker = zbusBroker;
    }
    @Autowired
    public void setShellService(ShellService shellService) {
        this.shellService = shellService;
    }
}

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

@ -1,5 +1,6 @@
package com.yihu.hos.arbiter.services;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.configuration.ArbiterServerConfiguration;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
@ -12,7 +13,6 @@ import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Consumer;
import org.zbus.net.http.Message;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@ -29,6 +29,8 @@ public class ShellService {
    private ArbiterServerConfiguration configuration;
    private ZbusBroker zbusBroker;
    private Consumer consumer;
    @Autowired
    private ObjectMapper objectMapper;
    public void proxy(Message message, Consumer consumer) {
@ -36,7 +38,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,10 +47,23 @@ public class ShellService {
            return;
        }
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_ARBITER + "@" + configuration.getTenant());
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {
            if (consumer != null) {
                consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_REQUEST + "@" + configuration.getTenant());
                String messageBodyString = consumer.queryMQ().getBodyString();
                Map<String, Object> message = objectMapper.readValue(messageBodyString, Map.class);
                Integer consumerCount = (Integer) message.get("consumerCount");
                if (consumerCount < 1) {
                    consumer.start(this::proxy);
                }
            } else {
                consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_REQUEST + "@" + configuration.getTenant());
                consumer.start(this::proxy);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }

+ 60 - 7
hos-broker/src/main/java/com/yihu/hos/broker/common/shell/SSHLinuxTool.java

@ -1,14 +1,13 @@
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 com.yihu.hos.core.file.FileUtil;
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,12 +92,12 @@ public class SSHLinuxTool {
            OutputStream outstream = channel.getOutputStream();
            //发送需要执行的SHELL命令,需要用\n结尾,表示回车
            String shellCommand = command + " \n";
            String shellCommand = command;
            outstream.write(shellCommand.getBytes());
            outstream.flush();
            //获取命令执行的结果
            Thread.sleep(2000);
            Thread.sleep(1000);
            if (instream.available() > 0) {
                byte[] data = new byte[instream.available()];
                int nLen = instream.read(data);
@ -106,8 +105,10 @@ public class SSHLinuxTool {
                    throw new Exception("network error.");
                }
                String result = FileUtil.readFileText(data);
                System.out.println("FileUtil獲取内容:"+result);
                //转换输出结果并打印出来
                String temp = new String(data, 0, nLen, "iso8859-1");
                String temp = new String(data, 0, nLen, "utf-8");
                System.out.println(temp);
                return temp;
            }
@ -125,4 +126,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";
}

+ 12 - 0
src/main/java/com/yihu/hos/common/CommonPageController.java

@ -1,6 +1,7 @@
package com.yihu.hos.common;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.remoteManage.service.RemoteShellService;
import com.yihu.hos.system.model.SystemUser;
import com.yihu.hos.tenant.model.TenantSession;
import com.yihu.hos.tenant.service.AuthenticateService;
@ -33,6 +34,8 @@ public class CommonPageController extends BaseController {
    @Autowired
    private AuthenticateService authenticateService;
    private RemoteShellService remoteShellService;
    /*
    登录页面
     */
@ -56,6 +59,8 @@ public class CommonPageController extends BaseController {
                } finally {
                    IOUtils.closeQuietly(out);
                }
            }else {
                remoteShellService.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
@ -98,6 +103,8 @@ public class CommonPageController extends BaseController {
            } finally {
                IOUtils.closeQuietly(out);
            }
        }else {
            remoteShellService.start();
        }
        } catch (Exception e) {
            e.printStackTrace();
@ -163,4 +170,9 @@ public class CommonPageController extends BaseController {
        model.addAttribute("contentPage","/common/home");
        return "partView";
    }
    @Autowired
    public void setRemoteShellService(RemoteShellService remoteShellService) {
        this.remoteShellService = remoteShellService;
    }
}

+ 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.";
}

+ 37 - 40
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,63 +38,57 @@ 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 = "租户名称")
//            @RequestParam(value = "tenant", required = false) String tenant,
            @ApiParam(name = "disCon", value = "是否断开会话连接")
            @RequestParam(value = "disCon", required = true) boolean disCon) {
        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(2000);
            String attachment = LocalContext.getContext().getAttachment(ContextAttributes.TENANT_NAME);
            result = LocalContext.getContext().getAttachment(ContextAttributes.SHELL_RESPONSE + attachment);
            int count = 0;
            while (result == null) {
                count++;
                Thread.sleep(2000);
                result = LocalContext.getContext().getAttachment(ContextAttributes.SHELL_RESPONSE + attachment);
                //获取失败时,尝试再一次获取结果
                if (count > 2) {
                    break;
                }
            }
            System.out.println("接口返回结果:" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}

+ 28 - 13
src/main/java/com/yihu/hos/remoteManage/service/RemoteShellService.java

@ -1,5 +1,6 @@
package com.yihu.hos.remoteManage.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.interceptor.LocalContext;
import com.yihu.hos.services.ServiceShellEventService;
@ -15,6 +16,7 @@ import org.zbus.net.http.Message;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
import java.util.Map;
/**
 * @author HZY
@ -31,15 +33,17 @@ public class RemoteShellService {
    private ServiceShellEventService serviceShellEventService;
    private ZbusBroker zbusBroker;
    private Consumer consumer;
    public static String backResult;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 发送shell命令消息
     *
     * @param command
     * @param disConnection
     * @return
     */
    public boolean sendShell(String command,boolean disConnection){
    public boolean sendShell(String command, boolean disConnection) {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
@ -58,10 +62,11 @@ public class RemoteShellService {
    }
    public void proxy(Message message, Consumer consumer) {
    public void handle(Message message, Consumer consumer) throws IOException {
        String bodyString = message.getBodyString();
        this.backResult=bodyString;
        String attachment = LocalContext.getContext().getAttachment(ContextAttributes.TENANT_NAME);
        LocalContext.getContext().setAttachment(ContextAttributes.SHELL_RESPONSE + attachment, bodyString);
        System.out.println("回调返回:" + bodyString);
    }
    public void start() {
@ -71,16 +76,28 @@ public class RemoteShellService {
        }
        String attachment = LocalContext.getContext().getAttachment(ContextAttributes.TENANT_NAME);
        if (attachment==null){
        if (attachment == null) {
            return;
        }
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_ADMIN + "@" + attachment);
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {
        try {
            if (consumer != null) {
                consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_RESPONSE + "@" + attachment);
                String messageBodyString = consumer.queryMQ().getBodyString();
                Map<String,Object> message = objectMapper.readValue(messageBodyString,Map.class);
                Integer consumerCount = (Integer) message.get("consumerCount");
                if (consumerCount<1) {
                    consumer.start(this::handle);
                }
            } else {
                consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_RESPONSE + "@" + attachment);
                consumer.start(this::handle);
            }
            System.out.println("start success~");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
@ -96,6 +113,4 @@ public class RemoteShellService {
        super.finalize();
    }
}

+ 20 - 0
src/main/java/com/yihu/hos/tenant/controller/TenantController.java

@ -180,6 +180,26 @@ public class TenantController extends BaseController{
        }
    }
    /**
     * 新建数据库
     * @param request
     * @return
     */
    @RequestMapping(value = "/createDB" , produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public Result createDB(HttpServletRequest request,
                           @ApiParam(name = "dbName", value = "数据库名称", allowMultiple = true)
                           @RequestPart() String dbName) {
        try {
            tenantService.createDB(dbName);
            return Result.success("新建数据库成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新建数据库失败!");
        }
    }
    /**
     *  //TODO 后 独立到对应的rest接口中

+ 4 - 1
src/main/java/com/yihu/hos/tenant/dao/TenantDao.java

@ -59,6 +59,9 @@ public class TenantDao extends SQLGeneralDAO {
    }
    public void createDB(String dbName) throws Exception {
        String sql = "CREATE DATABASE "+dbName;
        super.execute(sql);
    }
}

+ 5 - 0
src/main/java/com/yihu/hos/tenant/service/TenantService.java

@ -131,5 +131,10 @@ public class TenantService {
        }
    }
    @Transactional
    public Result createDB(String dbName) throws Exception {
        tenantDao.createDB(dbName);
        return Result.success("新建成功");
    }
}

+ 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',

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

@ -0,0 +1,37 @@
<%@ 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: 50%;
        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 style="font-size: 16px;font-weight: bold;">终端服务器控制台</label>
            </div>
        </div>
        <div class="m-form-group">
            <div class="m-form-control left" >
               <input type="checkbox" id="disCon" aria-valuetext="保持会话连接" checked="checked" />保持会话连接
            </div>
        </div>
    </div>
    <!--######菜单信息表######-->
    <div id="div_grid">
        <textarea id="main_text"></textarea>
    </div>
</div>

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

@ -0,0 +1,139 @@
<%@ 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){
            var disCon;
            var statuaValue = $("#disCon").ischecked;
            if("checked" == statuaValue){
                disCon = true;
            }else{
                disCon = false;
            }
            $.ajax({ //ajax处理
                type: "GET",
                url : "${contextRoot}/shell/sendShell",
                dataType : "json",
                data:{command:command,disCon:disCon},
                cache:false,
                success :function(data){
                    if(data.successFlg) {
                        var flg = data.successFlg;
                        if(flg){
                            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){
                            debugger
                            //TODO 字体颜色textare无法解析,所以暂时去除,后面看看有没有其他控件可以比较完美的支持
                            var content=data.message.myReplace("\\u001B\\[0m\\u001B\\[01;31m","").myReplace("\\u001B\\[0m","").myReplace("\\u001B\\[01;31m","").myReplace("\\u001B\\[01;34m","");
                            if(content.endsWith("]# ")){
                                $("#main_text").keydown(function(){
                                    PingBi(8);
                                });
                                $("#main_text").val(content);
                            }else{
                                $("#main_text").val(content+"\n ~]# ");
                                $("#main_text").keydown(function(){
                                    PingBi(8);
                                });
                            }
                        }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 PingBi(id){
        var command = $("#main_text").val();
        var arr=command.split("\r\n");
        var currentCommand = arr[0];
        var k=window.event.keyCode;
        /* 以]# 结束的一行,使之无法删除*/
        if(k==id && currentCommand.endsWith("]# ")){
            window.event.keyCode=0;
            window.event.returnValue=false;
            return false;
        }
    }
    String.prototype.myReplace=function(f,e){//吧f替换成e
        var reg=new RegExp(f,"g"); //创建正则RegExp对象
        return this.replace(reg,e);
    }
    $(function () {
        shell.init();
        shell.sendShell("\n");
    });
</script>