import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
public static void main(String[] args)
{
//得到Java进程的相关Runtime运行对象
Runtime runtime = Runtime.getRuntime();
try
{
//利用exec()方法执行shell 命令 ls -al /root ,并且返回一个Process对象 也就是子进程
//ps:这里都以最简单的shell命令举例。
Process process = runtime.exec("ls -al /root");
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
while ((temp = bufferReader.readLine()) != null)
{
stringBuffer.append(temp);
stringBuffer.append("
");
}
System.out.println(stringBuffer);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
publicclassShellExcuter{
privatestaticLoggerlogger= Logger.getLogger(ShellExcuter.class);
/**
* 跑linux命令
* @param cmd
* @param args
*/
publicstaticvoidrunShell(Stringcmd, String[] args) {
InputStreamin;
BufferedReaderbr;
OutputStreamout;
BufferedWriterbw;
try {
for (String arg : args) {
cmd = cmd +" "+arg;
}
//String[] cmds = new String[] {
//"/bin/sh",
//"-c",
//cmd };
logger.info(cmd);
Processprocess= Runtime.getRuntime().exec(cmd);
BufferedReaderbufferReader= newBufferedReader(newInputStreamReader(process.getInputStream()));
String temp = null;
while ((temp = bufferReader.readLine()) != null) {
logger.info(temp);
}
BufferedReaderbufferReader2= newBufferedReader(newInputStreamReader(process.getErrorStream()));
while ((temp = bufferReader.readLine()) != null) {
logger.info(temp);
}
bufferReader.close();
bufferReader2.close();
process.waitFor();
process.destroy();
} catch (Throwable e) {
logger.error("执行linux命令出错:"+ e.getMessage());
e.printStackTrace();
}
}
}