Java代码中执行shell脚本和命令

简介:

最近在项目中需要在一个接口中,传入shell命令作为参数,然后通过java来执行这个命令.
查了下资料发现可以使用Runtime.getRuntime().exec();这个方法来执行,下面是具体的代码.

Controller代码:

	@GetMapping("/exeShell")
    @ResponseBody
    public Result exeShell(String param, String command) {
	    /**
	    * 这里是简单的接口参数的校验
	    */
        if (!backDoorParam.equals(param)) {
            return Result.getFailResp(ErrorEnum.E_000004);
        }
        if (command == null) {
            return Result.getFailResp(ErrorEnum.E_000001);
        }
        logger.info("开始执行shell命令:{}", command);
        Process process = null;
	    //这里新建一个集和用来接收shell命令执行返回的打印结果
        List<String> processList = new ArrayList<String>();
        BufferedReader input = null;
        try {
        	// 这里直接将shell命令传入这个方法
            process = Runtime.getRuntime().exec(command);
            // 用输入流的方式从process中回去执行打印结果
            input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            // 将结果放入list集合
            while ((line = input.readLine()) != null) {
                processList.add(line);
            }
            input.close();
        } catch (Exception e) {
            logger.error("执行shell错误:{},错误:{}", command, e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    logger.error("关闭输入流错误:{}", e);
                }
            }
        }
        logger.info("执行shell脚本结束....");
        // 将结果返回
        return Result.getSuccessResp(processList.toString());
    }

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