Java执行Centos/Windows命令,异步执行,同步等待执行结果,输出命令执行日志等方法。
获取操作系统相关参数等信息
protected static final String LINUX_SHELL_PATH = "/bin/bash";
protected static final String WINDOWS_SHELL_PATH = "cmd.exe";
protected static final String LINUX_SHELL_PARAM = "-c";
protected static final String WINDOWS_SHELL_PARAM = "/c";
protected static final String LINUX_CHARSET_NAME = "UTF-8";
protected static final String WINDOWS_CHARSET_NAME = "GBK";
@Getter
@Setter
private SystemEnum systemEnum;
@Getter
@Setter
private String shellPath;
@Getter
@Setter
private String shellParam;
@Getter
@Setter
private String charsetName;
/**
* 执行shell命令
*
* @param cmd
* @throws IOException
*/
public void executeShell(String cmd) throws IOException {
this.executeShell(cmd, null);
}
public void executeShell(String cmd, File runDir) throws IOException {
String[] cmdArray = getCmdArray(cmd);
this.executeShell(cmdArray, runDir);
}
public void executeShell(String[] cmdArray) throws IOException {
this.executeShell(cmdArray, null);
}
public void executeShell(String[] cmdArray, File runDir) throws IOException {
executeWaitForEnd(cmdArray, runDir);
}
protected String[] getCmdArray(String cmd) {
String[] cmdArray = { shellPath, shellParam, cmd };
return cmdArray;
}
protected Process getProcess(String cmd) throws IOException{
return this.getProcess(cmd, null);
}
protected Process getProcess(String[] cmdArray) throws IOException{
return this.getProcess(cmdArray, null);
}
protected Process getProcess(String cmd, File runDir) throws IOException{
String[] cmdArray = getCmdArray(cmd);
return this.getProcess(cmdArray, runDir);
}
protected Process getProcess(String[] cmdArray, File runDir) throws IOException{
Runtime runComm = Runtime.getRuntime();
return runComm.exec(cmdArray, null, runDir);
}
public int executeWaitForEnd(String cmd) throws IOException {
return executeWaitForEnd(cmd, null);
}
public int executeWaitForEnd(String[] cmdArray) throws IOException {
return executeWaitForEnd(cmdArray, null);
}
public int executeWaitForEnd(String cmd, File runDir) throws IOException {
if (StringUtils.isBlank(cmd)) {
return -1;
}
Process ps = this.getProcess(cmd, runDir);
return executeWaitForEnd(ps);
}
public void executeWithLog(String cmd, File runDir) throws IOException {
if (StringUtils.isBlank(cmd)) {
return ;
}
Process ps = this.getProcess(cmd, runDir);
printLog(ps, charsetName);
}
public void executeWithLog(String[] cmdArray, File runDir) throws IOException {
if (cmdArray == null || cmdArray.length == 0) {
return ;
}
Process ps = this.getProcess(cmdArray, runDir);
printLog(ps, charsetName);
}
public int executeWaitForEnd(String[] cmdArray, File runDir) throws IOException {
if (cmdArray == null || cmdArray.length == 0) {
return -1;
}
Process ps = this.getProcess(cmdArray, runDir);
return executeWaitForEnd(ps);
}
public int executeWaitForEnd(Process ps) throws IOException {
try {
int i = ps.waitFor();
int exitValue = ps.exitValue();
log.info("command result: " + i + ";exitValue:" + exitValue);
return exitValue;
} catch (InterruptedException e) {
log.error("", e);
} finally {
IOUtils.closeQuietly(ps.getErrorStream());
IOUtils.closeQuietly(ps.getInputStream());
IOUtils.closeQuietly(ps.getOutputStream());
}
return -1;
}
/**
* 获取包含字符串processName的进程个数
*/
public int getProcessAmountByName(String processName) throws IOException {
List<String> resultList = this.getCmdExecResultStrList("ps -ef ");
if (resultList == null || resultList.isEmpty()) {
return 0;
}
int amount = 0;
for (int i = 0; i < resultList.size(); i++) {
String lineStr = resultList.get(i);
if (lineStr != null && lineStr.indexOf(processName) != -1) {
amount += 1;
}
}
return amount;
}
/**
* 获取包含字符串processName的进程列表
*/
public List<String> getProcessInfoByName(String processName) throws IOException {
List<String> resultList = this.getCmdExecResultStrList("ps -ef ");
List<String> processInfoList = new ArrayList<String>();
if (resultList == null || resultList.isEmpty()) {
return processInfoList;
}
for (int i = 0; i < resultList.size(); i++) {
String lineStr = resultList.get(i);
if (lineStr != null && lineStr.indexOf(processName) != -1) {
processInfoList.add(lineStr);
}
}
return processInfoList;
}
/**
* 获取复制字符串
*/
public String getCopyStr(String srcPath, String distPATH) {
return CommandStrUtils.getUnixCopyStr(srcPath, distPATH);
}
/**
* 获取文件下的文件个数
*/
public int getFileAmount(File file) throws IOException {
if (file == null || !file.exists()) {
return 1;
}
Runtime runComm = Runtime.getRuntime();
String[] cmdArray = getCmdArray("ls -lR|grep '^[-|d]'|wc -l");
Process ps = runComm.exec(cmdArray, null, file);
List<String> resultList = this.getCmdExecResultStrList(ps);
if (resultList == null || resultList.isEmpty()) {
return 0;
}
int fileAmount = 0;
for (String line : resultList) {
if (NumberUtils.isDigits(line)) {
fileAmount += Integer.parseInt(line);
break;
}
}
return fileAmount;
}
/**
* 为目录授权
*/
public void changeMod(File changeFile) throws IOException {
String[] cmdArray = getCmdArray("chmod -R a+wxr .");
Runtime runComm = Runtime.getRuntime();
Process ps = runComm.exec(cmdArray, null, changeFile);
this.executeWaitForEnd(ps);
}
public void diff(String bathPath, String newPath, String runPath, String resultFile) throws IOException {
StringBuffer buff = new StringBuffer().append("diff -rq ").append(bathPath).append(" ").append(newPath).append(" > ").append(resultFile);
String cmdArray[] = getCmdArray(buff.toString());
Runtime runComm = Runtime.getRuntime();
File runFile = new File(runPath);
Process ps = runComm.exec(cmdArray, null, runFile);
this.executeWaitForEnd(ps);
}
/**
* 判断该网站的Wget是否存在
*/
public boolean isWgetExist(String webUrl, List<String> processInfoList) throws IOException {
// 添加执行完成的链接
for (String processInfo : processInfoList) {
if (processInfo.indexOf(webUrl) != -1) {
return true;
}
}
return false;
}
/**
* 删除进程名称相关的所有进程
*/
public void killAllProcessByName(String processName) throws IOException {
String cmdStr = CommandStrUtils.getKillStrByName(processName);
this.executeShell(cmdStr);
}
/**
* 根据进程名称获取进程id列表
*/
public List<Integer> getPIdListByName(String processName) {
String cmd = "ps -ef|grep " + processName + "|grep -v grep|awk '{print $2}'";
String[] cmdArray = getCmdArray(cmd);
List<Integer> result = new ArrayList<Integer>();
try {
Runtime runComm = Runtime.getRuntime();
Process ps = runComm.exec(cmdArray);
List<String> resultList = this.getCmdExecResultStrList(ps);
if (resultList == null || resultList.isEmpty()) {
return result;
}
for (String line : resultList) {
Integer pid = Integer.parseInt(line);
result.add(pid);
}
} catch (Exception e) {
result = null;
log.error("", e);
}
return result;
}
public List<String> getCmdExecResultStrList(String cmd) throws IOException{
return this.getCmdExecResultStrList(cmd, null);
}
public List<String> getCmdExecResultStrList(String cmd, File runDir) throws IOException {
Process ps = this.getProcess(cmd, runDir);
return getCmdExecResultStrList(ps);
}
public List<String> getCmdExecResultStrList(Process ps) throws IOException {
return this.getCmdExecResultStrList(ps, charsetName);
}
public List<String> getCmdExecResultStrList(Process ps, String charsetName) throws IOException {
List<String> cmdExecResultStrList = new ArrayList<String>();
InputStreamReader isr = null;
BufferedReader br = null;
try {
isr = new InputStreamReader(ps.getInputStream(), charsetName);
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
cmdExecResultStrList.add(line);
}
} finally {
IOUtils.closeQuietly(isr);
IOUtils.closeQuietly(br);
IOUtils.closeQuietly(ps.getErrorStream());
IOUtils.closeQuietly(ps.getInputStream());
IOUtils.closeQuietly(ps.getOutputStream());
}
return cmdExecResultStrList;
}
public void printLog(Process ps, String charsetName) throws IOException {
InputStreamReader isr = null;
BufferedReader br = null;
try {
isr = new InputStreamReader(ps.getInputStream(), charsetName);
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
log.info(line);
}
} finally {
IOUtils.closeQuietly(isr);
IOUtils.closeQuietly(br);
IOUtils.closeQuietly(ps.getErrorStream());
IOUtils.closeQuietly(ps.getInputStream());
IOUtils.closeQuietly(ps.getOutputStream());
}
}
public StringBuffer getCmdExecResultBuffer(String commandStr, boolean isShell) throws IOException{
return getCmdExecResultBuffer(commandStr, isShell, null);
}
public StringBuffer getCmdExecResultBuffer(String commandStr, boolean isShell, File runDir) throws IOException {
StringBuffer buff = new StringBuffer();
Runtime runComm = Runtime.getRuntime();
Process ps = null;
if (isShell) {
String[] cmdArray = getCmdArray(commandStr);
ps = runComm.exec(cmdArray, null, runDir);
} else {
ps = runComm.exec(commandStr, null, runDir);
}
List<String> resultList = this.getCmdExecResultStrList(ps);
if (resultList == null || resultList.isEmpty()) {
return buff;
}
for (String line : resultList) {
buff.append(line);
}
return buff;
}
public void changeMod(String file) throws IOException {
File changeFile = new File(file);
this.changeMod(changeFile);
}
public String getSysVersion() {
String version = "5";
try {
StringBuffer buff = this.getCmdExecResultBuffer("cat /etc/redhat-release", true);
String sysinfo = buff.toString();
if (sysinfo.startsWith("CentOS release 5")) {
version = "5";
} else if (sysinfo.startsWith("CentOS release 6")) {
version = "6";
}
System.out.println("centos version is :" + version);
} catch (IOException e) {
log.error("", e);
}
return version;
}