java执行bat、exe等cmd命令

controller层

/**
 * Copyright © 2021. All rights reserved.
 *
 * @描述: 监控服务
 * @Prject: DataHub
 * @Package: com.domain.module.ops.message.controller
 * @ClassName: MonitorController
 * @date: 2022年6月21日
 * @version: V1.0
 */
package com.domain.module.ops.monitor.controller;

import com.domain.common.aop.Log;
import com.domain.common.response.HttpResponse;
import com.domain.common.response.HttpResponsePageList;
import com.domain.framework.controller.BaseController;
import com.domain.framework.service.BaseService;
import com.domain.module.ops.monitor.entity.MonitorEntity;
import com.domain.module.ops.monitor.service.MonitorService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @ClassName: MonitorController
 *  * @描述: 监控服务
 *  * @author: Eric
 *  * @date: 2022年6月21日
 */
@Log(value = "", name = "监控服务")
@RestController
@RequestMapping(value = "/ops/monitor")
public class MonitorController extends BaseController<MonitorEntity> {

    @Resource
    public MonitorService monitorService;

    @Override
    public BaseService<MonitorEntity> getBaseService() {
        return monitorService;
    }

    @Log(value = "获取服务启动状态", name = "")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public HttpResponsePageList<MonitorEntity> list() {
        return monitorService.getServerList();
    }

    @Log(value = "获取服务启动日志", name = "")
    @RequestMapping(value = "/getLog", method = RequestMethod.GET)
    public HttpResponse<String> list(String serverName,String port) {
        return monitorService.getLog(serverName,port);
    }

    @Log(value = "启动服务", name = "")
    @RequestMapping(value = "/startServer", method = RequestMethod.GET)
    public HttpResponse<String> startServer(String serverName,String port) {
        return monitorService.startServer(serverName,port);
    }

    @Log(value = "关闭服务", name = "")
    @RequestMapping(value = "/stopServer", method = RequestMethod.GET)
    public HttpResponse<String> stopServer(String serverName,String port) {
        return monitorService.stopServer(serverName,port);
    }

    @Log(value = "地图服务访问情况统计", name = "")
    @RequestMapping(value = "/statisticServiceType", method = RequestMethod.GET)
    public HttpResponse<String> statisticServiceType() {
        return monitorService.statisticServiceType();
    }

}


service层

/**
 * Copyright © 2021. All rights reserved.
 *
 * @描述: 消息中心
 * @Prject: DataHub
 * @Package: com.domain.module.ops.message.service
 * @ClassName: OpinionServiceImpl
 * @author: Eric
 * @date: 2022年6月6日
 * @version: V1.0
 */
package com.domain.module.ops.monitor.service;

import com.alibaba.fastjson.JSONObject;
import com.domain.common.response.HttpResponse;
import com.domain.common.response.HttpResponsePageList;
import com.domain.common.response.PageList;
import com.domain.framework.dao.BaseDao;
import com.domain.framework.service.BaseServiceImpl;
import com.domain.module.ops.monitor.dao.MonitorDao;
import com.domain.module.ops.monitor.entity.MonitorEntity;
import com.domain.module.res.registerresources.service.RegisterResourcesService;
import com.domain.module.store.file.dao.FileDao;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName: MonitorServiceImpl
 * @描述: 监控服务
 * @author: Eric
 * @date: 2022年5月16日
 */
@Service
public class MonitorServiceImpl extends BaseServiceImpl<MonitorEntity> implements MonitorService {
    @Resource
    public MonitorDao monitorDao;
    @Value("${nginx.logsUrl}")
    public String NGINX_LOG_URL;
    @Resource
    public RegisterResourcesService registerResourcesService;
    @Autowired
    FileDao fileDao;
    @Resource
    org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate template;

    private static String readFile(File file) {
        List<String> list = new ArrayList<>();
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "gbk");
            BufferedReader bw = new BufferedReader(isr);
            String line = null;
            while ((line = bw.readLine()) != null) {
                list.add(line);
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer text = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            String[] st = list.get(i).split("\t");
            for (int j = 0; j < st.length; j++) {
                text.append(st[j]);
            }
        }
        return text.toString();
    }

    @Override
    public BaseDao<MonitorEntity> getBaseDao() {
        return monitorDao;
    }

    @Override
    public HttpResponsePageList<MonitorEntity> getServerList() {
        String baseUrlStr = NGINX_LOG_URL + "bat_logs";
        try {
            File[] serverList = new File(baseUrlStr).listFiles();
            if (serverList != null || serverList.length > 0) {
                Stream<File> fileStream = Stream.of(serverList);
                List<MonitorEntity> MonitorList = fileStream.map(n -> {
                    String nameStr = n.getName();
                    boolean contains = nameStr.contains("-");
                    String sName = "";
                    String sPort = "";
                    Boolean sStatus = false;
                    StringBuffer cmdStr = new StringBuffer();
                    if (contains) {
                        String[] splitName = nameStr.split("-");
                        sName = splitName[0];
                        sPort = splitName[1].replace(".log", "");
                        cmdStr.append("cmd /c netstat -aon|findstr ").append(sPort);
                    } else {
                        sName = nameStr.replace(".log", "");
                        cmdStr.append("tasklist  /fi \"imagename eq " + sName + ".exe\"");
                    }
                    String result = startBatShell(cmdStr.toString());
                    sStatus = (result == null || result.equals("") || result.contains("信息")) ? false : true;
                    String fileContext = readFile(n);
                    return new MonitorEntity(sName, sPort, sStatus, fileContext);
                }).collect(Collectors.toList());
                return new HttpResponsePageList<MonitorEntity>(new PageList<>(MonitorList));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HttpResponsePageList<MonitorEntity>();
    }

    @Override
    public HttpResponse<String> getLog(String serverName, String port) {
        String baseUrlStr = NGINX_LOG_URL.split("/DMS/")[0] + "/DMS/";
        switch (serverName) {
            case "nginx":
                baseUrlStr += "online_datahub/logs/";
                String index = "access-" + LocalDate.now().toString(); //access-2022-06-23
                File nginxLog = new File(baseUrlStr + index + ".log");
                if (nginxLog.exists()) {
                    String readFile = readFile(nginxLog);
                    serverName = readFile;
                }
                break;
            case "mapserver":
                baseUrlStr += "service_engine/mapserver/log/app.log";
                serverName = readLog(baseUrlStr);
                break;
            case "rasterserver":
                baseUrlStr += "service_engine/rasterserver/log/app.log";
                serverName = readLog(baseUrlStr);
                break;
            case "elasticsearch":
                baseUrlStr += "system_plugins/elasticsearch/logs/elasticsearch.log";
                serverName = readLog(baseUrlStr);
                break;
            case "server_controller":
                baseUrlStr += "server_controller/logs/";
                String scIndex = "catalina." + LocalDate.now().toString();
                File scLog = new File(baseUrlStr + scIndex + ".log");
                if (scLog.exists()) {
                    String readFile = readFile(scLog);
                    serverName = readFile;
                }
                break;
            default:
                String path = (port == null || "".equals(port)) ? NGINX_LOG_URL + "bat_logs/" + serverName + ".log" : NGINX_LOG_URL + "bat_logs/" + serverName + "-" + port + ".log";
                File batLog = new File(path);
                if (batLog.exists()) {
                    String readFile = readFile(batLog);
                    serverName = readFile;
                }
                break;
        }

        return new HttpResponse<>(serverName);
    }

    @Override
    public HttpResponse<String> stopServer(String serverName, String port) {
        String os = System.getProperty("os.name").toLowerCase();
        String cmdStr = "";
        if (os.contains("windows")) {
            if (port.equals("") || null == port) {
                cmdStr = "taskkill /f /t /im " + serverName + ".exe";
            } else {
                String getPidStr = "netstat -ano|findstr " + port;
                String startBatShell = startBatShell(getPidStr);
                if (startBatShell.length() > 0) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(
                            new ByteArrayInputStream(startBatShell.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
                    String readLine = null;
                    try {
                        readLine = br.readLine();
                        if (readLine != null && readLine.contains("LISTENING")) {
                            String pidStr = readLine.split("LISTENING")[1].trim();
                            cmdStr = "taskkill /pid " + pidStr + " /f";
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            startBatShell(cmdStr);
        }
        return new HttpResponse<>(serverName + "已停止");
    }

    @Override
    public HttpResponse<String> startServer(String serverName, String port) {
        String baseUrlStr = NGINX_LOG_URL.split("/DMS/")[0] + "/DMS/";
        switch (serverName) {
            case "mapserver":
            case "rasterserver":
                baseUrlStr += "service_engine/" + serverName + "/";
                startBatShell("cmd /c start cd " + baseUrlStr + " && start /d \"" + baseUrlStr + "\" " + serverName + ".exe");
                break;
            case "online_datahub":
                baseUrlStr += "online_datahub/";
                startBatShell("cmd /c start " + baseUrlStr + "server.bat");
                break;
            case "server_controller":
                baseUrlStr += "server_controller/bin/startup.bat";
                startBatShell("cmd /c start " + baseUrlStr);
                break;
            case "server_manager":
                baseUrlStr += "service_engine/server-manager/";
                startBatShell("cmd /c start " + baseUrlStr + "server.bat");
                break;
        }
        return new HttpResponse<>(serverName + "已启动");
    }

    @Override
    public HttpResponse<String> statisticServiceType() {
        IndexCoordinates index = IndexCoordinates.of("filebeat-log*");
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.boolQuery());
        builder.withFields("message", "@timestamp");
        NativeSearchQuery searchQuery = builder.build();
        SearchHits<JSONObject> scroll = template.search(searchQuery, JSONObject.class, index);
        Iterator<SearchHit<JSONObject>> iterator = scroll.iterator();
        Long rasterTotal = 0L;
        Long mapTotal = 0L;
        Long rasterDate = 0L;
        Long mapDate = 0L;
        String tempMapDate = "";
        String tempRasterDate = "";
        ArrayList<Map> mapList = new ArrayList<>();
        ArrayList<Map> rasterList = new ArrayList<>();
        ArrayList<Map> shareList = new ArrayList<>();
        while (iterator.hasNext()) {
            JSONObject content = iterator.next().getContent();
            String message = content.getString("message");
            String date = content.getString("@timestamp").split("T")[0];
            if (message.contains("/mapserver/")) {
                mapTotal++;
                if (date.equals(tempMapDate) || tempMapDate.equals("")) {
                    tempMapDate = date;
                    mapDate++;
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("mapDate", tempMapDate);
                    map.put("mapValue", mapDate);
                    mapList.add(map);
                    mapDate = 0L;
                    tempMapDate = date;
                }
            } else if (message.contains("/rasterserver/")) {
                rasterTotal++;
                if (date.equals(tempRasterDate) || tempRasterDate.equals("")) {
                    tempRasterDate = date;
                    rasterDate++;
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("rasterDate", tempRasterDate);
                    map.put("rasterValue", rasterDate);
                    rasterList.add(map);
                    rasterDate = 0L;
                    tempRasterDate = date;
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("mapDate", tempMapDate);
        map.put("mapValue", mapDate);
        mapList.add(map);
        map = new HashMap<>();
        map.put("rasterDate", tempRasterDate);
        map.put("rasterValue", rasterDate);
        rasterList.add(map);
        Map<String, Object> res = new HashMap<>();
        res.put("mapTotal", mapTotal);
        res.put("rasterTotal", rasterTotal);
        res.put("mapDateCount", mapList);
        res.put("rasterDateCount", rasterList);
        List<Object[]> objects = fileDao.countFileType();
        res.put("storeFile", objects);
        List<Map<String, Object>> downloadList = registerResourcesService.resourceDownLoadCount();
        res.put("download", downloadList);
        Map<String, Object> shareType = registerResourcesService.registerCount();
        res.put("shareType", shareType);
        return new HttpResponse<>(JSONObject.toJSONString(res));
    }

    private String readLog(String baseUrlStr) {
        String log = "";
        File file = new File(baseUrlStr);
        if (file.exists()) {
            log = readFile(file);
        }
        return log;
    }

    String startBatShell(String cmd) {
        try {
            Process psServe = Runtime.getRuntime().exec(cmd);
            psServe.waitFor();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(psServe.getInputStream(), "gbk"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}


注意,执行exe时不能直接start,得先cd进去,比如cmd /c start cd E:/Work/File//路网计算程序 && start /d "E:/Work/File/路网计算程序" RdFLSim.exe注意/d命令后面有引号将xxx.exe分开了


版权声明:本文为weixin_42707397原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。