java bash linux_Java调用linux命令及Shell脚本

7306bbcca1b4e87077938f56843792cf.png

==================

package com.wll.shell;

import java.util.List;

public class ShellResult {

public static final int SUCCESS = 0;

public static final int ERROR = 1;

public static final int TIMEOUT = 13;

private int errorCode;

private List description;

public int getErrorCode() {

return errorCode;

}

public void setErrorCode(int errorCode) {

this.errorCode = errorCode;

}

public List getDescription() {

return description;

}

public void setDescription(List description) {

this.description = description;

}

@Override

public String toString() {

return "ShellResult{" +

"errorCode=" + errorCode +

", description=" + description +

'}';

}

}

=======================

package com.wll.shell;

public class ShellTest {

public static void main(String[] args) {

String cmd = "";

if (args.length == 1) {

cmd = args[0];

}

cmd="sleep 5";

ShellUtils.runShell(cmd);

}

}

=======================

package com.wll.shell;

import com.wll.utils.CommonUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ShellUtils {

private static final Logger LOGGER = LoggerFactory.getLogger(ShellUtils.class);

private static final long THREAD_SLEEP_TIME = 10;

private static final int DEFAULT_WAIT_TIME = 20 * 60 * 1000;

public static void runShell(String cmd) {

String[] command = new String[]{"/bin/sh", "-c", cmd};

try {

Process process = Runtime.getRuntime().exec(command);

ShellResult result = getProcessResult(process, DEFAULT_WAIT_TIME);

LOGGER.info("Command [{}] executed successfully.", cmd);

LOGGER.info(result.toString());

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 获取命令执行结果

* @param process 子进程

* @param waitTime 指定超时时间

* @return 命令执行输出结果

*/

public static ShellResult getProcessResult(Process process, long waitTime) {

ShellResult cmdResult = new ShellResult();

boolean isTimeout = false;

long loopNumber = waitTime / THREAD_SLEEP_TIME;

long realLoopNumber = 0;

int exitValue = -1;

StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());

StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());

errorGobbler.start();

outputGobbler.start();

try {

while (true) {

try {

Thread.sleep(THREAD_SLEEP_TIME);

exitValue = process.exitValue();

break;

} catch (InterruptedException e) {

realLoopNumber++;

if (realLoopNumber >= loopNumber) {

isTimeout = true;

break;

}

}

}

errorGobbler.join();

outputGobbler.join();

if (isTimeout) {

cmdResult.setErrorCode(ShellResult.TIMEOUT);

return cmdResult;

}

cmdResult.setErrorCode(exitValue);

if (exitValue != ShellResult.SUCCESS) {

cmdResult.setDescription(errorGobbler.getOutput());

} else {

cmdResult.setDescription(outputGobbler.getOutput());

}

} catch (InterruptedException e) {

LOGGER.error("Get shell result error.");

cmdResult.setErrorCode(ShellResult.ERROR);

} finally {

CommonUtils.closeStream(process.getErrorStream());

CommonUtils.closeStream(process.getInputStream());

CommonUtils.closeStream(process.getOutputStream());

}

return cmdResult;

}

}

=======================

package com.wll.shell;

import com.wll.utils.CommonUtils;

import java.io.*;

import java.util.ArrayList;

import java.util.List;

public class StreamGobbler extends Thread {

private InputStream is;

private List output = new ArrayList();

public StreamGobbler(InputStream is) {

this.is = is;

}

public List getOutput() {

return output;

}

@Override

public void run() {

BufferedReader reader = null;

try {

reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

String line = "";

while ((line = reader.readLine()) != null) {

output.add(line);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

CommonUtils.closeStream(reader);

}

}

}

=======================

package com.wll.utils;

import org.apache.log4j.Logger;

import java.io.Closeable;

import java.io.IOException;

public class CommonUtils {

private static final Logger LOGGER = Logger.getLogger(CommonUtils.class);

/**

* 提供统一关闭流的方法

*

* @param stream 待关闭的流

*/

public static void closeStream(Closeable stream) {

if (stream == null) {

return;

}

try {

stream.close();

} catch (IOException e) {

LOGGER.error("Close stream failed!");

}

}

}

=======================

log4j.rootLogger=debug, ServerDailyRollingFile, stdout

log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender

log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd

log4j.appender.ServerDailyRollingFile.File=notify-subscription.log

log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout

log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d - %m%n

log4j.appender.ServerDailyRollingFile.Append=true

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %p [%c] %m%n

=======================

错误:

Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited

at java.lang.UNIXProcess.exitValue(UNIXProcess.java:423)

at com.wll.shell.ShellUtils.getProcessResult(ShellUtils.java:53)

at com.wll.shell.ShellUtils.runShell(ShellUtils.java:22)

at com.wll.shell.ShellTest.main(ShellTest.java:10)

解决方法:

package com.wll.shell;

public class ShellTest {

public static void main(String[] args) {

String cmd = "";

if (args.length == 1) {

cmd = args[0];

}

cmd="sleep 5";

try {

Process prc = Runtime.getRuntime().exec(cmd);

prc.waitFor();

} catch (Exception e) {

// TODO: handle exception

}

}

}

=======================

以下代码可以运行bash文件,

bash文件必须可以执行 chmod a+x filename;

dos2unix filename;

String[] path=new String[]{"sh","/home/aiin/cons_workspace/conmotif/src/conotif/testbash.txt" };

try{

Runtime runtime = Runtime.getRuntime();

Process pro = runtime.exec(path);

int status = pro.waitFor();

if (status != 0)

{

System.out.println("Failed to call shell's command");

}

BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));

StringBuffer strbr = new StringBuffer();

String line;

while ((line = br.readLine())!= null)

{

strbr.append(line).append("\n");

}

String result = strbr.toString();

System.out.println(result);

}

catch (IOException ec)

{

ec.printStackTrace();

}

catch (InterruptedException ex){

ex.printStackTrace();

}

=======================

REF

https://www.cnblogs.com/163yun/p/9661724.html

=======================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值