1.Windows 很簡單,寫出來時為了和linux對比
public void execWindowsCmd(String cmd) throws Exception {
Runtime rt = Runtime.getRuntime();
Process ppp = rt.exec(cmd);
//input
InputStreamReader ir = new InputStreamReader(ppp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null)
com.pub.Log.logger.debug(this.getClass().getClass() + " " +
line);
//error
ir = new InputStreamReader(ppp.getErrorStream());
input = new LineNumberReader(ir);
while ((line = input.readLine()) != null)
com.pub.Log.logger.debug(this.getClass().getClass() + " " +
line);
ppp.waitFor();
}
2. Linux :首先要確保對于命令,允許Web服務器的用戶是否有權限,普通命令和windows沒什么區別。Linux管道命令不能這樣直接執行,下面是具體實現fang
public void execLinuxCmd(String cmd) throws Exception {
Runtime rt = Runtime.getRuntime();
File f = new File(this.fileName + PDU_SHELL);
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("#!/bin/bash");
bw.newLine();
bw.write(cmd); //把命令寫入一個文本shell文件
bw.flush();
bw.close();
cmd = f.getAbsolutePath();
Process ppp = rt.exec("chmod a+x " + cmd); //授權該shell文件可以執行
ppp.waitFor();
ppp = rt.exec(cmd); //執行shell
//input
InputStreamReader ir = new InputStreamReader(ppp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null)
com.pub.Log.logger.debug(this.getClass().getClass() + " " +
line);
//error
ir = new InputStreamReader(ppp.getErrorStream());
input = new LineNumberReader(ir);
while ((line = input.readLine()) != null)
com.pub.Log.logger.debug(this.getClass().getClass() + " " +
line);
ppp.waitFor();
}