Open xuchuanyin opened 5 years ago
private static Process getExecRuntimeProcess(String cmdStr)
{
if (null == cmdStr)
{
//已知方法参数为null,直接传递null而不是参数名
return null;
}
cmdStr = cmdStr.replaceAll("\\\\", "/");
//Validate the cmd string
Pattern splitPattern = Pattern.compile("[ ]+");
String[] cmdArr = splitPattern.split(cmdStr);
if (!validateCommand(cmdArr))
{
return null;
}
//execute the cmd string
Runtime rt = Runtime.getRuntime();
if (null == rt)
{
return null;
}
Process rs = null;
try
{
rs = rt.exec(cmdArr);
}
catch (IOException e)
{
return null;
}
return rs;
}
class StreamGobbler implements Runnable { private static final InforSightLogger LOGGER = new InforSightLogger(StreamGobbler.class);
private InputStream is;
private String result;
private final int max_stream_length = 10240;
StreamGobbler(InputStream is)
{
this.is = is;
}
public String getResult()
{
return result;
}
public void run()
{
BoundedInputStream bis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try
{
bis = new BoundedInputStream(is, max_stream_length);
isr = new InputStreamReader(bis, "UTF-8");
br = new BufferedReader(isr, 2048);
StringBuilder output = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
{
output.append(line);
output.append(System.lineSeparator());
}
result = output.toString();
LOGGER.info(result);
}
catch (IOException e)
{
result = e.getMessage();
}
finally
{
try
{
if (null != bis)
{
bis.close();
}
if (null != isr)
{
isr.close();
}
if (null != br)
{
br.close();
}
}
catch (IOException e)
{
LOGGER.warn("Error occurs when close reader", e);
}
}
}
}
public static boolean validateCommand(final String[] cmdArray)
{
boolean result = true;
if (cmdArray != null)
{
for (int i = 0; i < cmdArray.length; i++)
{
if (cmdArray[i] == null || !cmdArray[i].matches("[\\\\/:0-9a-zA-Z\\s\\-_\\.@&*\\${}\";,()=$]+"))
{
result = false;
break;
}
}
}
else
{
result = false;
}
return result;
}