首页 > 系统相关 >linux java调用sh脚本

linux java调用sh脚本

时间:2023-06-18 21:45:16浏览次数:64  
标签:java String process commandList return sh linux import null

1、

2、

import org.jeecg.zhongyi.auto_dep.util.CommandStreamGobbler;
import org.jeecg.zhongyi.util.LogbackUtil;
import org.jeecg.zhongyi.util.vo.Result;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class auto_dep_helper {
    public static Result dep_env_wait(String cmd_sh) {
        Process process = null;
        List<String> commandList = new LinkedList<>();
        //commandList.add("/data/xxxxx/admin_xx_auto_deployment.sh");
        commandList.add(cmd_sh);
        commandList.add("hello world ");
        String[] commands = new String[commandList.size()];
        for (int i = 0; i < commandList.size(); i++) {
            commands[i] = commandList.get(i);
        }
        InputStreamReader stdISR = null;
        InputStreamReader errISR = null;

        String logName = cmd_sh;
        try {
            process = Runtime.getRuntime().exec(commands);

            CommandStreamGobbler errorGobbler = new CommandStreamGobbler(process.getErrorStream(), logName, "ERR");
            CommandStreamGobbler outputGobbler = new CommandStreamGobbler(process.getInputStream(), logName, "STD");

            errorGobbler.start();
            // 必须先等待错误输出ready再建立标准输出
            while (!errorGobbler.isReady()) {
                Thread.sleep(10);
            }
            outputGobbler.start();
            while (!outputGobbler.isReady()) {
                Thread.sleep(10);
            }

            int exitValue = process.waitFor();
            System.out.println("exitValue=" + exitValue);
            if (exitValue == 0) {
                LogbackUtil.getErrorLogger().info("更新部署成功");
                return Result.success();
            } else {
                LogbackUtil.getErrorLogger().info("更新部署失败");
                return Result.error();
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            LogbackUtil.getErrorLogger().error(e.getMessage(), e);
            return Result.error(e.getMessage());
        } finally {
            try {
                if (stdISR != null) {
                    stdISR.close();
                }
                if (errISR != null) {
                    errISR.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (IOException e) {
                System.out.println("正式执行命令:" + logName + "有IO异常");
                LogbackUtil.getErrorLogger().error(e.getMessage(), e);
                return Result.error(e.getMessage());
            }
        }
    }

    public static Result dep_env_not_wait(String cmd_sh) {
        Process process = null;
        List<String> commandList = new LinkedList<>();
        //commandList.add("/data/xxxxx/admin_xx_auto_deployment.sh");
        commandList.add(cmd_sh);
        commandList.add("hello world ");
        String[] commands = new String[commandList.size()];
        for (int i = 0; i < commandList.size(); i++) {
            commands[i] = commandList.get(i);
        }
        InputStreamReader stdISR = null;
        InputStreamReader errISR = null;

        String logName = cmd_sh;
        try {
            process = Runtime.getRuntime().exec(commands);

            CommandStreamGobbler errorGobbler = new CommandStreamGobbler(process.getErrorStream(), logName, "ERR");
            CommandStreamGobbler outputGobbler = new CommandStreamGobbler(process.getInputStream(), logName, "STD");

            errorGobbler.start();
            // 必须先等待错误输出ready再建立标准输出
            while (!errorGobbler.isReady()) {
                Thread.sleep(10);
            }
            outputGobbler.start();
            while (!outputGobbler.isReady()) {
                Thread.sleep(10);
            }

            boolean exitValue = process.waitFor(5, TimeUnit.SECONDS);
            System.out.println("exitValue=" + exitValue);
            if (exitValue) {
                LogbackUtil.getErrorLogger().info("更新部署成功,请稍等,并验证结果");
                return Result.success("更新部署成功,请稍等,并验证结果");
            } else {
                LogbackUtil.getErrorLogger().info("更新部署失败,请稍等,并验证结果");
                return Result.error("更新部署超时,请稍等,并验证结果");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            LogbackUtil.getErrorLogger().error(e.getMessage(), e);
            return Result.error(e.getMessage());
        } finally {
            try {
                if (stdISR != null) {
                    stdISR.close();
                }
                if (errISR != null) {
                    errISR.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (IOException e) {
                System.out.println("正式执行命令:" + logName + "有IO异常");
                LogbackUtil.getErrorLogger().error(e.getMessage(), e);
                return Result.error(e.getMessage());
            }
        }
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

public class CommandStreamGobbler extends Thread {

    private InputStream is;

    private String command;

    private String prefix = "";

    private boolean readFinish = false;

    private boolean ready = false;

    private List<String> infoList = new LinkedList<String>();

    public CommandStreamGobbler(InputStream is, String command, String prefix) {
        this.is = is;
        this.command = command;
        this.prefix = prefix;
    }

    public void run() {
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            ready = true;

            while (br != null && (line = br.readLine()) != null) {
                infoList.add(line);
                System.out.println(prefix + " line: " + line);
                LogbackUtil.getErrorLogger().info(prefix + " line: " + line);
            }
        } catch (IOException ioe) {
            System.out.println("正式执行命令:" + command + "有IO异常");
            LogbackUtil.getErrorLogger().error("正式执行命令:" + command + "有IO异常", ioe);
        } finally {
            try {
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException ioe) {
                System.out.println("正式执行命令:" + command + "有IO异常");
                LogbackUtil.getErrorLogger().error("正式执行命令:" + command + "有IO异常", ioe);
            }
            readFinish = true;
        }
    }

    public InputStream getIs() {
        return is;
    }

    public String getCommand() {
        return command;
    }

    public boolean isReadFinish() {
        return readFinish;
    }

    public boolean isReady() {
        return ready;
    }

    public List<String> getInfoList() {
        return infoList;
    }
}

标签:java,String,process,commandList,return,sh,linux,import,null
From: https://www.cnblogs.com/kikyoqiang/p/17489806.html

相关文章

  • linux sh脚本一键自动部署 前端项目、docker项目、java项目
    1、2、静态前端,admin_xx_auto_deployment.sh#!/bin/bashsource/etc/profile#.~/.bash_profilecd/data/yyyyy_temp/xx_admin_code/yyyyy2-admingitpullPATH=$PATH:./node_modules/.binecho$PATHnpmrunbuild:test1cp-r/data/yyyyy_temp/xx_admin_code/yyyyy2-ad......
  • SQL调优:让Java内存分担计算
    作者: 剽悍一小兔我们在工作中,经常会因为一条慢sql调半天。这一节,我给大家介绍一种提升查询效率的思路,那就是让Java内存帮我们分担一些运算。案例还是采用springBoot日记本系统,源码下载地址和教程在文末。先改一个BUG之前遗留了一个BUG需要我们解决,就是在日记的详情页,日记类型没......
  • Java百炼成仙1.1 他叫叶小凡
    第1章陨铁山脉篇1.1他叫叶小凡“这里是哪里?”男子揉了揉有些迷糊的脑袋,环顾四周,只见一望无际的平原。他的白色服饰在强烈的阳光下发出闪亮的光芒,仿佛是一抹清新的色彩点缀在这沉寂的荒野之中。天空中阳光透过透明的大气层倾泻而下,温暖的光线照耀着男子苍白的脸庞。空气中的尘埃让......
  • linux 安装node16
    1、在Linux系统安装Nodejshttps://nodejs.org/download/release/v16.20.0/node-v16.20.0-linux-x64.tar.gzhttps://nodejs.org/download/release/v16.20.0/https://nodejs.org/download/release/2、yum-yinstallgccmakegcc-c++openssl-develwgetcd/root/k/tools/n......
  • 【Nexus】Linux安装Nexus
    目录一、安装包获取方式1、Nexus3.49版本的安装包2、Nexus3.53版本的安装包二、下载安装包的两种方式(建议使用第一种安装方式)1、直接把下载好的安装包上传到服务器中2、通过wget安装Nexus压缩包①、可以使用以下命令进行安装Nexus的最新版本②、也可以点击官网复制想要下载的Nexus......
  • Java代码精简之道-10条代码精简方案
    场景一、Java中利用try-with-resource语句JDK7开始新增了对需要关闭资源处理的特殊语法try-with-resource。所有实现Closeable接口的“资源”,均可采用try-with-resource进行简化。例如InputStream,OutputStream,Connection,Statement,ResultSet等接口都实现了,使用try-with-reso......
  • Java多线程-Lesson01-线程的创建
    线程创建的三种方式继承Thread类步骤:继承Thread类重写run()方法调用start()开启线程重写run()方法:@Overridepublicvoidrun(){for(inti=0;i<200;i++){System.out.println("run():"+i);}} run()方法里面就是我们多......
  • An Introduction to Linux Automation, Tools and Techniques
    AnIntroductiontoLinuxAutomation,ToolsandTechniqueshttps://linuxconfig.org/an-introduction-to-linux-automation-tools-and-techniquesInthefast-pacedworldoftechnology,automatingroutinetaskscanbethekeytoincreasedefficiencyandproducti......
  • 关于Linux系统下Lua编程运行环境的部署安装
    这里以操作系统:RedHatEnterpriseLinuxrelease8.7(Ootpa)为例,讲解如下部署Lua编程脚本的运行环境首先对于Lua脚本,需要保证系统中有lua二进制程序文件,即/usr/bin/lua但最小化安装的Linux- RedHatEnterpriseLinuxrelease8.7(Ootpa) 笔者试了一下,没有lua命令了 ......
  • 必知必会:Java基础
    创建对象有几种方式(1)new创建对象;(2)反射创建对象;(3)采用clone机制;(4)序列化机制。创建反射对象的几种方式(1)类.class:通过 类名.class 创建反射获取对象; 类.class 是静态加载,是JVM编译时就要加载。Class<ClassDemo>oClass=ClassDemo.class;(2) object.getClass() :以 实......