java调用shell脚本基础代码

应用场景

在某个时间点重启项目
定时监控项目启动(可以用更好的方法)

解释

用法

可以写定时任务调用这个脚本
可以用系统界面调用这个脚本

参数

第一个参数是shell脚本的位置和名字,第二个是等这个脚本启动几分钟,第三个是否打印shell脚本的输出

主要代码

package com.boc.quartz.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

@Component("scriptTask")
@Slf4j
public class ScriptTask {
	
	/**
     * 
     * @param shell_path shell脚本的位置和名字 当前路径下的脚本 './test.sh'
     * @param wait_minutes 等几分钟
     * @param printShellOut 是否打印脚本日志 N/Y
     */
	public void callShell(String shell_path, Integer wait_minutes , String printShellOut) {
		// 获取shell返回流
        BufferedInputStream in = null;
        // 字符流转换字节流
        BufferedReader br = null;
        
        if(printShellOut==null) printShellOut="N";
        
        try{
            //shell执行状态
            // 定义传入shell脚本的参数,将参数放入字符串数组里
            String cmds[] = new String[1];
            cmds[0] = shell_path;
            // 执行shell脚本
            log.debug("Execute Shell : "+shell_path);
            Process pcs = Runtime.getRuntime().exec(cmds);
            try {
                log.debug("Execute Shell ["+shell_path+"]  wait "+wait_minutes+" MINUTES");
                pcs.waitFor(wait_minutes, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                log.error("Execute Shell ["+shell_path+"] has Exception", e.getMessage());
            }
            log.debug("Execute ShellTask ["+shell_path+"] finished.");
            
            if(printShellOut.toUpperCase().equals("Y")) {
            	log.debug("Execute ShellTask ["+shell_path+"] result print start.");
            	in = new BufferedInputStream(pcs.getInputStream());
                // 字符流转换字节流
                br = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = br.readLine()) != null) {
                    log.debug("ExecuteShellTask result:",line);
                }
                log.debug("Execute ShellTask ["+shell_path+"] result print end.");
            }
            
        }catch (Exception ex){
            log.error("ShellTask Exception", ex.getMessage());
        }finally {
            // 关闭输入流
        	try {
        		if(printShellOut.toUpperCase().equals("Y")) {
	        		br.close();
	                in.close();
        		}
        	}catch(Exception e) {
        		log.error("ShellTask Exception", e.getMessage());
        	}
            
        }
	}

}




  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值