import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class CommandRun {
private java.lang.Process p;
private InputStream is;
private OutputStream os;
private BufferedWriter bw;
private BufferedReader br;
// private ProcessBuilder pb;
private InputStream stdErr;
/**
* @date Sep 4, 2014
* @auther jiaj.zhou@sunyard.com
* @param args
*/
public static void main(String[] args) {
CommandRun cr = new CommandRun();
String osn = cr.getSystem();
String line = "";
BufferedReader bufr = null;
try {
bufr = new BufferedReader(new InputStreamReader(System.in));
while ((line = bufr.readLine()) != null) {
System.out.println("[osname : " + osn + "][recive command : " + line + "]");
if ("bye".equals(line)) {
break;
}
String result = "";
if(osn.equals("windows")){
/*open cmd*/
cr.p = Runtime.getRuntime().exec("cmd");
cr.os = cr.p.getOutputStream();
cr.is = cr.p.getInputStream();
// stdErr = p.getErrorStream();
result = cr.windowRun(line);
}else if(osn.equals("linux")){
result = cr.linuxRun(line);
}
System.out.println("******return string start******\r\n" + result + "\r\n" + "*******return string end*******");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(bufr != null){
try {
bufr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* linuxMethod
* @date Sep 4, 2014
* @auther jiaj.zhou@sunyard.com
* @param line
* @return
* @throws Exception
*/
public String linuxRun(String line) throws Exception{
String [] commands = { "sh", "-c", " " };
commands[2] = line;
p = Runtime.getRuntime().exec(commands);
p.waitFor();
return readInfo(p.getInputStream());
}
/**
* windowsMethod
* @date Sep 4, 2014
* @auther jiaj.zhou@sunyard.com
* @param line
* @return
*/
public String windowRun(String line){
String result = "";
try {
bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write(line);
bw.newLine();
bw.flush();
bw.close();
int n = p.waitFor();
result = readInfo(is);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* return info
* @date Sep 4, 2014
* @auther jiaj.zhou@sunyard.com
* @param is
* @return
*/
private String readInfo(InputStream is){
StringBuffer resStr = new StringBuffer("");
br = new BufferedReader(new InputStreamReader(is));
String buffer = "";
try {
while ((buffer = br.readLine()) != null) {
resStr.append(buffer + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return resStr.toString();
}
/**
* os
* @date Sep 4, 2014
* @auther jiaj.zhou@sunyard.com
* @return
*/
private String getSystem(){
String osName = "";
if (System.getProperty("os.name").startsWith("Windows")){
osName = "windows";
}else{
osName = "linux";
}
return osName;
}
}