CmdController.java 2.6 KB
package com.tianbo.analysis.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

@Controller
@Slf4j
public class CmdController {

    @RequestMapping("/linuxCmd")
    public String linuxCmd(@RequestParam(value = "command",required = false) String command,Model model){
        List<String> strList = new ArrayList();
        try {
            if (command !=null && !command.isEmpty()){
                Process process;
                process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command}, null, null);
                InputStreamReader ir = new InputStreamReader(process
                        .getInputStream());
                LineNumberReader input = new LineNumberReader(ir);
                String line;
                process.waitFor();
                while ((line = input.readLine()) != null) {
                    strList.add(line);
                    log.info(line);
                }
                model.addAttribute("cmdResult",strList);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("执行命令出错",e);
        }



        return "cmd/cmd";
    }

    @RequestMapping("/windowsCmd")
    public String windowsCmd(@RequestParam(value = "command",required = false) String command,Model model){
        List<String> strList = new ArrayList();
        try {
            if (command !=null && !command.isEmpty()){
                Runtime rt = Runtime.getRuntime();
                String[] args = new String[]{"cmd","/c",command};
                Process pr = rt.exec(args,null,null);
                //Process pr = rt.exec("cmd /c dir"); // cmd /c calc
                // Process pr = rt.exec("D:\\xunlei\\project.aspx");

                BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));

                String line;

                while ((line = input.readLine()) != null) {
                    strList.add(line);
                    log.info(line);
                }

                int exitVal = pr.waitFor();
                log.info("exitVal",exitVal);
                model.addAttribute("cmdResult",strList);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("执行命令出错",e);
        }
        return "cmd/wincmd";
    }
}