Java操作shell脚本

本文介绍了一个Java实现的命令执行器类,该类可以执行外部命令并返回执行结果,支持设置命令执行的超时时间,并记录命令执行的日志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Exec {

private static ILogger logger = LoggerFactory.getLogger(Exec.class);

public Exec() {
super();
}


    /**
     * 执行命令(如Shell脚本)<br>
     * 
     * @param cmd 操作命令
     * @param timeout 超时时间
     * @return 命令执行过程输出内容
     * 
     * @throws IOException
     * @throws TimeoutException
     * @throws InterruptedException
     */
    public String execute(final String cmd, final long timeout) throws IOException, TimeoutException, InterruptedException{
    if(cmd == null || cmd.trim().length() == 0) {
    return null;
    }
    long time = 1000L * 5;
    time = timeout > 0 ? timeout : time;
        
    long begin = System.currentTimeMillis();
   
    logger.info("Begin execute command { " + cmd + " }, timeout = " + time + " seconds.");
        
    //执行命令
    Process process = Runtime.getRuntime().exec(cmd); 
        
        TimeWorker timeWorker = new TimeWorker(process);
        process.getOutputStream().close();
        OutputWorker outputWorker = new OutputWorker(process.getInputStream());
        String result = null;
        outputWorker.start();
        timeWorker.start();
        try {
       
        //任务超时
            timeWorker.join(time);
            if (timeWorker.exit == null) {
                throw new TimeoutException(cmd);
            } else if(timeWorker.exit != 0) {
            logger.error("Execute command " + cmd + " error, error message: " + this.getOutput(process.getErrorStream()));
                result = "error";
            } else {
                result = outputWorker.output;
            }
        } catch (InterruptedException e) {
            timeWorker.interrupt();
            Thread.currentThread().interrupt();
            throw e;
        } finally {
            process.destroy();
        }
        
        long end = System.currentTimeMillis();
        logger.info("Finish execute command { " + cmd + " }, time spent " + (end - begin)/1000L + " seconds.");
   
    return result;
    }
    
    /**
     * 获取IO输出内容 <br>
     * 
     * @param stream 流
     * @return 内容
     * @throws IOException
     */
    private String getOutput(InputStream stream) throws IOException {
    if(stream == null) {
    return null;
    }
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        String line = null;
        while((line = reader.readLine()) != null) {
            buffer.append(line + "\n");
        }
        reader.close();
        return buffer.toString().trim();
    }
    
    /**
     * 
     * @author 
     *
     */
    private static class OutputWorker extends Thread {
   
        private final InputStream stream;
        private String output = null;


        private OutputWorker(InputStream stream) {
            this.stream = stream;
        }
        
        public void  run() {
            String line = null;
            StringBuffer buffer=new StringBuffer();
            BufferedReader reader=null;
            try {
                reader = new BufferedReader(new InputStreamReader(stream));
                while((line = reader.readLine()) != null) {
                    buffer.append(line+"\n");
                }
                this.output = buffer.toString().trim();
            } catch (IOException e) {
            logger.error(e.getMessage());
            } finally {
                if(reader!=null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                    logger.error(e.getMessage());
                    }
                }
            }
        }


    }
    
    /**
     * 
     * @author
     *
     */
    private static class TimeWorker extends Thread {
   
        private final Process process;
        
        private Integer exit = null;


        private TimeWorker(Process process) {
            this.process = process;
        }
        
        public void run() {
            try {
            //阻塞等待命令执行结束
                exit = process.waitFor();
            } catch (InterruptedException e) {
            logger.error(e.getMessage());
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值