1.需求场景

使用java调用shell脚本,直接与Linux服务器交互,并执行远程服务器发邮件任务。

2.项目环境

普通java项目

3.解决方法

(1)java调用shell脚本

package com.demo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class ShellUtil {
	private static final int SUCCESS = 0;	
    private static final String SUCCESS_MESSAGE = "successful";
    private static final String ERROR_MESSAGE = "fail";
    /**
     * 
    * @Title: executer 
    * @Description: TODO
    * @param command
    * @return
     */
    public static boolean executer(String[] command){
        try{
        	Process process=Runtime.getRuntime().exec(command);
            readProcessOutput(process);
            // 等待程序执行结束并输出状态
            int exitCode = process.waitFor();
            if (exitCode == SUCCESS) {
                System.out.println(SUCCESS_MESSAGE);
                return true;
            } else {
                System.err.println(ERROR_MESSAGE + exitCode);
            }
        }catch(Exception e){
        	e.printStackTrace();
        }
        return false;
    }
    
    /**
     * 输出打印信息
    * @Title: readProcessOutput 
    * @Description: TODO
    * @param process
     */
    private static void readProcessOutput(final Process process) {
	        // 将进程的正常输出在 System.out 中打印,进程的错误输出在 System.err 中打印
	        read(process.getInputStream(), System.out);
	        read(process.getErrorStream(), System.err);
	    }
    
    private static void  read(InputStream inputStream, PrintStream out) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                out.println(line);
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
    	executer("tail -f /data/demo/test.log");
    }
}

(2)异步执行脚本

public void runShell(String param1,String param2){
       final String  commend[] = {"/data/demo/test.sh",param1,param2};
			 ExecutorService cachedThreadPool = Executors.newCachedThreadPool();  
             cachedThreadPool.execute(new Runnable() {  
                 public void run() {  
                 	ShellUtil.executer(commend);//耗时任务
                 }  
             });  
             cachedThreadPool.shutdown();  
}


Logo

更多推荐