Java调用linux命令及Shell脚本

 

 

 

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

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<String> description;
 
    public int getErrorCode() {
        return errorCode;
    }
 
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
 
    public List<String> getDescription() {
        return description;
    }
 
    public void setDescription(List<String> 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<String> output = new ArrayList<String>();

 

    public StreamGobbler(InputStream is) {

        this.is = is;

    }

 

    public List<String> 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/tohxyblog/p/6501396.html

https://www.cnblogs.com/x_wukong/p/5148152.html

https://blog.csdn.net/u010512607/article/details/80659422

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

 

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

 

posted @ 2020-10-21 10:44  emanlee  阅读(953)  评论(0编辑  收藏  举报