package org.jeecg.common.util;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
@Slf4j
public class CommandUtil {
public static String run(String command) throws IOException {
Scanner input = null;
String result = "";
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
try {
process.waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.error("==================获取进程号命令有错误:[{}]=============",e.getMessage(), e);
}
InputStream is = process.getInputStream();
input = new Scanner(is);
while (input.hasNextLine()) {
result += input.nextLine() + "\n";
}
result = command + "\n" + result;
} finally {
if (input != null) {
input.close();
}
if (process != null) {
process.destroy();
}
}
return result;
}
public static String run(String[] command) throws IOException {
Scanner input = null;
String result = "";
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
try {
process.waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.error("执行获取相机当前进程的命令报错====>[{}]",e.getMessage(), e);
}
InputStream is = process.getInputStream();
input = new Scanner(is);
while (input.hasNextLine()) {
result += input.nextLine() + "\n";
}
result = command + "\n" + result;
} finally {
if (input != null) {
input.close();
}
if (process != null) {
process.destroy();
}
}
return result;
}
}
执行下面命令 获取ffmpeg 所有端口号,保存到指定的文件目录下
ps -ef | grep ffmpeg | grep -v 'grep' | awk '{print $2}' > /app/data/video/portFile.txt
java 执行以上linux命令
StringBuffer sb = new StringBuffer();
String command = sb.append("ps -ef | grep ffmpeg | grep -v 'grep' | awk '{print $2}' > ")
.append(portFile).append("/portFile.txt").toString();
List<String> commandArr = new ArrayList<>();
commandArr.add("/bin/sh");
commandArr.add("-c");
commandArr.add(command);
CommandUtil.run(commandArr.toArray(new String[commandArr.size()]));
Thread.sleep(1000);