ProcessBuilder pb = new ProcessBuilder(cmds);
pb.redirectErrorStream(true);
Process exec = pb.start();
public static void main(String[] args) {
String cmd2 = "dmidecode -s system-serial-number";//获取Linux系统主板序列号
String serResult2 = doLinuxCmd(cmd2);
}
/**
* 方法说明:执行linux命令
* @param cmdStr 需要执行的linux命令
* @return 执行命令后的输出(如果是启动一个进程,则可能一直无法返回)
*/
public static String doLinuxCmd(String cmdStr) throws IOException {
Process exec = doLinuxCmdNoOut(cmdStr);
InputStream inputStream = (InputStream) exec .getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder builder = new StringBuilder();
try {
String temp;
while ((temp = bufferedReader.readLine()) != null) {//控制台输出
builder.append(temp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
}
log.info("linux返回值: " + builder.toString());
return builder.toString();
}
/**
* 方法说明:执行linux命令
* @param cmdStr 命令
* @return
*/
public static Process doLinuxCmdNoOut(String cmdStr) throws IOException {
ArrayList<String> cmds = new ArrayList<String>();
cmds.add("bash");
cmds.add("-c");
cmds.add(cmdStr);
ProcessBuilder pb = new ProcessBuilder(cmds);
pb.redirectErrorStream(true);
Process exec = pb.start();
return exec;
}