最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Java调用Linux命令并得到返回值

XAMPP相关 admin 162浏览 0评论

Java调用Linux命令并得到返回值

talk is cheep, show you the code directly!

@RequestMapping(value = "/execShell", method = RequestMethod.GET)
public String processRequest(HttpServletRequest request, HttpServletResponse response) {
    String command = request.getParameter("cmd");
    logger.info("linux cmd={}", command);
    long start = System.currentTimeMillis();
    Process process = null;
    StringBuilder result = new StringBuilder();
    try {
        process = Runtime.getRuntime().exec("/bin/"+ command);
        try {
            process.waitFor(10L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            logger.error("", e);
        }
        try (InputStream inputStream = process.getInputStream()) {
            byte[] bytes = new byte[1024];
            while (inputStream.read(bytes) != -1) {
                result.append(new String(bytes)).append("\n");
            }
        }
    } catch (IOException e) {
        logger.error("", e);
        result.append(ExceptionUtils.getMessage(e));
    } finally {
        if (process != null) {
            process.destroy();
        }
        result.append("\nduration=").append(System.currentTimeMillis() - start);
    }
    return command + "\n" + result.toString();


}

 

转载请注明:XAMPP中文组官网 » Java调用Linux命令并得到返回值

您必须 登录 才能发表评论!