java程序执行,调用shell命令和shell脚本

  坑呀!记得在start()之后, waitFor()之前把缓冲区读出来打log,否则是阻塞缓冲区,没有输出的

package com.jikexueyuancrm.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.util.List;

import org.apache.log4j.Logger;

import com.jikexueyuancrm.controller.AnHui;

/**
 * ShellUtils
 * <ul>
 * <strong>Check root</strong>
 * <li>{@link ShellUtils#checkRootPermission()}</li>
 * </ul>
 * <ul>
 * <strong>Execte command</strong>
 * <li>{@link ShellUtils#execCommand(String, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String, boolean, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(List, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(List, boolean, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String[], boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String[], boolean, boolean)}</li>
 * </ul>
 * 
 * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-5-16
 */
/**
 * @author yuan hai
 * 使用Runtime.getRuntime().exec
 */
public class ShellUtils {

    
    
    
    private static Logger log = Logger.getLogger(ShellUtils.class);
    
    public static final String COMMAND_SU       = "su";
    public static final String COMMAND_SH       = "sh";
    public static final String COMMAND_EXIT     = "exit\n";
    public static final String COMMAND_LINE_END = "\n";

    private ShellUtils() {
        throw new AssertionError();
    }

    /**
     * check whether has root permission
     * 
     * @return
     */
    public static boolean checkRootPermission() {
        return execCommand("echo root", true, false).result == 0;
    }

    /**
     * execute shell command, default return result msg
     * 
     * @param command command
     * @param isRoot whether need to run with root
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(String command, boolean isRoot) {
        return execCommand(new String[] {command}, isRoot, true);
    }

    /**
     * execute shell commands, default return result msg
     * 
     * @param commands command list
     * @param isRoot whether need to run with root
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(List<String> commands, boolean isRoot) {
        return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, true);
    }

    /**
     * execute shell commands, default return result msg
     * 
     * @param commands command array
     * @param isRoot whether need to run with root
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(String[] commands, boolean isRoot) {
        return execCommand(commands, isRoot, true);
    }

    /**
     * execute shell command
     * 
     * @param command command
     * @param isRoot whether need to run with root
     * @param isNeedResultMsg whether need result msg
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
        return execCommand(new String[] {command}, isRoot, isNeedResultMsg);
    }

    /**
     * execute shell commands
     * 
     * @param commands command list
     * @param isRoot whether need to run with root
     * @param isNeedResultMsg whether need result msg
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(List<String> commands, boolean isRoot, boolean isNeedResultMsg) {
        return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, isNeedResultMsg);
    }

    /**
     * execute shell commands
     * 
     * 
     * 最基础方法
     * @param commands command array
     * @param isRoot whether need to run with root
     * @param isNeedResultMsg whether need result msg
     * @return <ul>
     *         <li>if isNeedResultMsg is false, {@link CommandResult#successMsg} is null and
     *         {@link CommandResult#errorMsg} is null.</li>
     *         <li>if {@link CommandResult#result} is -1, there maybe some excepiton.</li>
     *         </ul>
     */
    public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, null);
        }

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;

        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command == null) {
                    continue;
                }

                // donnot use os.writeBytes(commmand), avoid chinese charset error
                os.write(command.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
            }
            os.writeBytes(COMMAND_EXIT);
            os.flush();

          
            // get command result
            if (isNeedResultMsg) {
                successMsg = new StringBuilder();
                errorMsg = new StringBuilder();
                successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s).append("\n");
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s).append("\n");
                }
            }
            
            result = process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (process != null) {
                process.destroy();
            }
        }
        
        log.info("result:"+result);
       if( successMsg != null) log.info("successMsg:"+successMsg.toString());
       
       if( errorMsg != null) log.info("errorMsg:"+errorMsg.toString());
       
        return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
                : errorMsg.toString());
    }

    /**
     * result of command
     * <ul>
     * <li>{@link CommandResult#result} means result of command, 0 means normal, else means error, same to excute in
     * linux shell</li>
     * <li>{@link CommandResult#successMsg} means success message of command result</li>
     * <li>{@link CommandResult#errorMsg} means error message of command result</li>
     * </ul>
     * 
     * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2013-5-16
     */
    public static class CommandResult {

        /** result of command **/
        public int    result;
        /** success message of command result **/
        public String successMsg;
        /** error message of command result **/
        public String errorMsg;

        public CommandResult(int result) {
            this.result = result;
        }

        public CommandResult(int result, String successMsg, String errorMsg) {
            this.result = result;
            this.successMsg = successMsg;
            this.errorMsg = errorMsg;
        }
    }
    
    
    
    

public static void main(String[] args) throws Exception {  
    
    //
    
    String[] cmd=new String[]{"ps aux","pwd","ls -al"};
    //执行shell命令
//    execCommand(cmd,false, true);
    //执行shell脚本
    String[] script=new String[]{"/bin/bash /home/smgadmin/test/soyoung_comment/shell/crawler.sh start  "};
    
    execCommand(script,false, true);
    
//使用ProcessBuilder    
//    exeCmd("ps aux;ls -al;pwd");//执行linux命令
//    exeCmd("dir&dir");//执行windows命令一行多命令用&分隔
    
} 

//使用ProcessBuilder

/**
 * @author yuan hai 2016年12月9日
 * @param shell  shell可以传入多个命令  ,例如:"ps aux;ls -al;pwd"
 * @return
 * @throws IOException
 */
public  static int exeCmd(String shell) throws IOException {  
      int success = 0;  
      StringBuffer sb = new StringBuffer();  
      BufferedReader br = null;  
      
      // get name representing the running Java virtual machine.  
      String name = ManagementFactory.getRuntimeMXBean().getName();  
      String pid = name.split("@")[0];  
      
      try {  
        System.out.println("Starting to exec{ " + shell + " }. PID is: " + pid);  
        Process process = null; 
        
        //执行脚本时,不要加-c  
       // 当执行系统的命令时,才会加-c
        //linux命令行
        ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", shell);  
        //windows命令行
      //  ProcessBuilder pb = new ProcessBuilder("cmd", "/c", shell);
        
        pb.environment();  
        pb.redirectErrorStream(true); // merge error stream into standard stream  
        process = pb.start();  
        if (process != null) {  
          br = new BufferedReader(  
              new InputStreamReader(process.getInputStream(),"GBK"), 1024);  
        
        } else {  
          System.out.println("There is no PID found.");  
        }  
        sb.append("Ending exec right now, the result is:\n");  
        String line = null;  
        while (br != null && (line = br.readLine()) != null) {  
          sb.append(line).append("\n");  
        }  
        
        //记得在start()之后, waitFor()之前把缓冲区读出来打log
        process.waitFor();  
      } catch (Exception ioe) {  
        sb.append("Error occured when exec cmd:\n").append(ioe.getMessage()).append("\n");  
      } finally {  
        PrintWriter writer = null;  
        if (br != null) {  
          br.close();  
        }  
        try {  
          writer = new PrintWriter(System.out);  
          writer.write(sb.toString());  
        } catch (Exception e) {  
          log.error(e.getMessage(), e);  
        } finally {  
          writer.close();  
        }  
        success = 1;  
      }  
      return success;  
    }  
    
    
}

参考文章:

阿里大牛文章:

https://yq.aliyun.com/articles/2362

时间: 2024-08-02 10:55:33

java程序执行,调用shell命令和shell脚本的相关文章

深入理解Java程序执行顺序

下面将从一道阿里巴巴试题详细分析Java程序执行顺序. 阿里巴巴试题 public class Test { public static int k = 0; public static Test t1 = new Test("t1"); public static Test t2 = new Test("t2"); public static int i = print("i"); public static int n = 99; publi

java 程序执行输出有两种简单方式

java 程序执行输出有两种简单方式: 1. System.out.println("需要输出的内容"): 该方法可参看运行一个简单的Java程序 结果图: 2. System.out.print("需要输出的内容"): 1 public class HelloWorld 2 { 3 //Java程序的入口方法,程序将从这里开始运行 4 public static void main(String[] args) 5 { 6 //向控制台打印一条语句 7 Syste

perl程序执行时的命令行参数

perl命令行参数默认存储在perl自定义变量@ARGV中.#判断参数个数是否为0,根据上下文环境这里就是==符号,这里@ARGV指的是命令行参数数组元素个数if(@ARGV == 0)# 这里@ARGV指的是命令行参数数组,对数据元素遍历,打印出每个元素,这里的$_为foreach的默认自增变量foreach(@ARGV){ print "$_\n";}# $#ARGV表示@ARGV数组的最后一个元素的下标,该语句同样打印出数组中的每个元素,$ARGV[0]表示@ARGV数组的第0个

java程序执行SQL脚本文件

首先引入ibatis-common-2.jar包 import com.ibatis.common.jdbc.ScriptRunner; import com.ibatis.common.resources.Resources; jpetstore测试代码如下: package com.ibatis.jpetstore.test; import java.sql.DriverManager; import java.util.Properties; import com.ibatis.commo

java程序执行sql文件

List<String> sqlFileList = new ArrayList<String>();从文件读放内容到按分号放到sqlFileListpublic List<String> readSqlFiles(List<String> fileNameList) {List<String> sqlList = new ArrayList<String>();for (String fileName : fileNameList)

java程序执行过程&amp;基本数据类型

1. 程序load到内存. 2. 找到程序入口方法(main())开始执行. 3. 程序在内存中的存放 3.1 代码段(code segment)--------存放代码 3.2 数据段(data segment)--------存放静态变量,字符串常量 3.3 栈(stack)                ----------存放局部变量 3.4 堆(heap)                -----------存放new出来的东西 ----------------------------

java程序中调用dos shell命令 -- 此处以调用doc命令为例

/**  *  Java调用windows的DOS命令  */ public class RunDocInJava{     public static void main(String[] args) {         InputStream ins = null;         String[] cmd = new String[] { "cmd.exe", "/c", "ipconfig" };  // 命令行         try 

重复调用ab命令的shell代码和整理ab结果的java代码

先说下问题产生的背景,因为要做压力测试,频繁使用ab命令,需要测试好多项,每项测试要做10遍以上,测试完了还要画测试结果曲线,又因为公司内网不稳定,测十遍都找不到个准确值,所以只能在别人下班时测试.但是问题是,一旦服务器改了配置,就要把所有测试再做一遍,而且只能晚上测,而且只能晚上测,而且只能晚上测...重要的事情说三遍.所以我想啊,晚上测试,白头干啥?于是白天写脚本了,晚上运行一下,早上来看结果,做做曲线图. ab命令是一个很好的网站压力测试工具, 在mac下,查看帮助为 man ab 在li

Java程序执行Linux命令(JSP运行其他程序)

java程序中要执行linux命令主要依赖2个类:Process和Runtime 首先看一下Process类: ProcessBuilder.start() 和 Runtime.exec 方法创建一个本机进程,并返回 Process 子类的一个实例,该实例可用来控制进程并获得相关信息.Process 类提供了执行从进程输入.执行输出到进程.等待进程完成. 检查进程的退出状态以及销毁(杀掉)进程的方法. 创建进程的方法可能无法针对某些本机平台上的特定进程很好地工作,比如,本机窗口进程,守护进程,M