Java获取Linux下Top命令的执行结果
package com.ncs_cyber.util;
import Java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Random;
public class GwUtil {
private static Random r = new Random();
/**
* 功能:执行CMD命令,返回命令结果
*/
public static String execByFile(String cmd) throws Exception {
String filename = null;
StringBuffer sb = new StringBuffer("");
BufferedReader bufferedReader = null;
Process process = null;
File file = null;
r.setSeed(99999);
if (cmd == null) {
return null;
}
try {
String ls_1;
// 生成临时文件,文件名随机
filename = "/tmp/gwtemp" + Long.toString(Math.abs(r.nextLong()))
+ ".sh";
file = new File(filename);
while (file.exists()) {
filename = "/tmp/gwtemp"
+ Long.toString(Math.abs(r.nextLong())) + ".sh";
file = new File(filename);
}
String execmd = new String("sh " + filename);// 执行文件的命令
FileWriter filewriter = new FileWriter(file, false);
filewriter.write("#! /bin/sh");
// Log.debug("do cmd:" + cmd + "\n");
filewriter.write("\n" + cmd + "\n");// 将命令写入文件
filewriter.close();
// Log.debug("run cmd\n");
process = Runtime.getRuntime().exec(execmd); // 执行临时的可执行文件
// Log.debug("run cmd over\n");
// 得到结果
bufferedReader = new BufferedReader(new InputStreamReader(process
.getInputStream()));
while ((ls_1 = bufferedReader.readLine()) != null) {
sb.append(ls_1 + "\n");
}
} catch (Exception e) {
throw new Exception("can not exec the cmd:" + cmd);
} finally { // 清理
try {
filename = null;
if (file != null) {
file.delete();
file = null;
}
if (bufferedReader != null) {
bufferedReader.close();
bufferedReader = null;
}
if (process != null) {
process.destroy();
process = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static void main(String args[]){
try {
GwUtil.execByFile("top -bn -1>/tmp/test.txt;cat/tmp/test.txt");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}