Apache Commons Exec 工具包的使用

洪弘毅
2023-12-01

在没有使用这个工具包之前 我都手写代码去执行linux命令的,因为自己写代码去执行linux返回的信息不全,因为写得很简单只是调用没有用线程去等待信息的返回,也没有实现失效时间,后来想自己实现但是在无意间找到了这个工具包,能实现我的需求,当时很兴奋。

commons exec下载路径

 

版本下载1.3的版本即可,其实也只有一个版本可下载

1.简单的命令执行

public static void execLinuxCommand(String command){

  if(StringUtils.isEmpty(command)){

    LOG.info("执行的Linux命令不能为空");

    return ;

  }

  //定义命令行对象

  CommandLine commandLine = new CommandLine(command);

  try{

    //定义执行器对象

    Executor executor = new DefaultExecutor();

    //如果在执行命令结束后发生异常,是因为没有设置结束标识值

    executor.setExitValue(1);

    executor.execute(commandLine);

  } catch (Exceptiion ex){

    LOG.info("执行Linux命令失败",ex);

  }

}

2.将执行命令结果信息

try{

  //定义执行结果信息输出

  ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

  //定义失效时间(单位/亳秒)

  ExecuteWatchdog watchdog = new ExecuteWatchdog(3*1000);

  PumpStreamHandler streamHandler = new PumpStreamHandler(byteStream);

  execute.setStreamHandler(streamHandler);

  execute.setWatchdog(watchdog);

}catch(Exception ex){

  

}

在定义StreamHandler后他内置了打印的方法

转载于:https://www.cnblogs.com/ulxkj/p/4181877.html

 类似资料: