springboot启动bat/bash脚本实现过程

 更新时间:2025年08月28日 16:45:17   作者:诚诚程程成  
请提供具体错误信息或脚本内容,以便分析Spring Boot项目中Controller、Entity、Service层的依赖问题,跨平台脚本需注意路径兼容性和环境变量配置,确保依赖项正确引入

windows有两个脚本,linux有一个脚本,需要用springboot启动着两个脚本

contoller层

import com.dwc.putdatasystem.service.impl.PutServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@RestController
@RequestMapping("/putbat")
public class PutController {

    @Autowired
    private PutServiceImpl putBatService;



    @GetMapping ("bat")
    public void put() throws Exception {
        //第一部分   执行bat脚本
        String batPath = "D:/******/package.bat"; // bat脚本路径
        String batPath2 ="D:/*****/put.bat";
        File batFile = new File(batPath);
        boolean batFileExist = batFile.exists();
        System.out.println("😊😊😊😊😊😊😊😊😊😊😊😊😊判断bat脚本文件是否存在(true/false)😊😊😊😊😊😊😊😊😊😊😊😊😊");
        System.out.println("batFileExist:" + batFileExist);
        if (batFileExist) {
            System.out.println("😊😊😊😊😊😊😊😊😊😊😊😊😊正在执行编译ing😊😊😊😊😊😊😊😊😊😊😊😊😊");
            putBatService.callCmd(batPath);
            System.out.println("😊😊😊😊😊😊😊😊😊😊😊😊😊编译完成😊😊😊😊😊😊😊😊😊😊😊😊😊");
            System.out.println("😊😊😊😊😊😊😊😊😊😊😊😊😊正在上传至linux系统ing😊😊😊😊😊😊😊😊😊😊😊😊😊");
            putBatService.callCmd(batPath2);
        }
        System.out.println("😊😊😊😊😊😊😊😊😊😊😊😊😊jar包上传服务器完成😊😊😊😊😊😊😊😊😊😊😊😊😊");

        //第二部分  执行bash脚本
        String linuxIP = "ip地址";
        String usrName = "用户名";
        String passwd  = "密码";
        String DEFAULTCHART = "UTF-8";
        //PutEntity rec = new PutEntity(linuxIP, usrName, passwd,);

        //PutBatServiceImpl putBatService = new PutBatServiceImpl(linuxIP, usrName, passwd);

        System.out.println("😊😊😊😊😊😊😊😊😊😊😊😊😊正在上传job至集群ing😊😊😊😊😊😊😊😊😊😊😊😊😊");
        // 执行脚本
        System.out.println(putBatService.execute("/home/dwc/bin/flinkrunjar1.sh start", linuxIP, usrName, passwd, DEFAULTCHART));
        // 执行jps命令,查看节点是否完整
        System.out.println(putBatService.execute("/home/dwc/bin/jpsall start", linuxIP, usrName, passwd, DEFAULTCHART));
        System.out.println("😊😊😊😊😊😊😊😊😊😊😊😊😊job上传集群完成😊😊😊😊😊😊😊😊😊😊😊😊😊");
    }



}

entity层

import ch.ethz.ssh2.Connection;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Value;

@Data
public class PutEntity {

    public String DEFAULTCHART = "UTF-8";
    public Connection conn;
    public String ip;
    public String userName;
    public String userPwd;


    public PutEntity(String ip, String userName, String userPwd, String DEFAULTCHART) {
        this.ip = ip;
        this.userName = userName;
        this.userPwd = userPwd;
        this.DEFAULTCHART = DEFAULTCHART;
    }

    public PutEntity() {

    }
}

service层

import java.io.InputStream;

public interface PutService {

    //win脚本用
    void callCmd(String locationCmd);

    //linux脚本用
    //Boolean login(String ip, String userName, String userPwd, String DEFAULTCHART) throws Exception;

    String execute(String cmd, String ip, String userName, String userPwd, String DEFAULTCHART) throws Exception;

    String processStdout(InputStream in, String charset) throws Exception;
}
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.dwc.putdatasystem.entity.PutEntity;
import com.dwc.putdatasystem.service.PutService;
import ch.ethz.ssh2.Connection;
import org.apache.flink.calcite.shaded.org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;


import org.springframework.stereotype.Service;

import java.io.*;


@Service("PutBatService")
public class PutServiceImpl implements PutService {


    @Override
    public void  callCmd(String locationCmd){
        StringBuilder sb = new StringBuilder();
        try {
            Process child = Runtime.getRuntime().exec(locationCmd);
            InputStream in = child.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in));
            String line;
            while((line=bufferedReader.readLine())!=null)
            {
                sb.append(line + "\n");
            }
            in.close();
            try {
                child.waitFor();
            } catch (InterruptedException e) {
                System.out.println(e);
            }
            System.out.println("sb:" + sb.toString());
            System.out.println("callCmd execute finished");
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    /**
     * 远程登录linux主机
     * @return 登录成功返回true,否则返回false
     */
//    @Override
//    public Boolean login(String ip, String userName, String userPwd, String DEFAULTCHART) throws Exception {
//        PutEntity putEntity = new PutEntity(ip, userName, userPwd, DEFAULTCHART);
//        boolean flg = false;
//        try {
//            putEntity.conn = new Connection(ip);
//            // 连接
//            putEntity.conn.connect();
//            // 认证
//            flg = putEntity.conn.authenticateWithPassword(userName, userPwd);
//        } catch (IOException e) {
//            throw new Exception("远程连接服务器失败", e);
//        }
//        return flg;
//    }

    /**
     * 远程执行shll脚本或者命令
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    @Override
    public String execute(String cmd, String ip, String userName, String userPwd, String DEFAULTCHART) throws Exception {
        //根据传来的ip、userName、userPwd、DEFAULTCHART创建putEntity
        PutEntity putEntity = new PutEntity(ip,userName,userPwd,DEFAULTCHART);
        String result = "";  //result得到命令执行完后返回的结果值
        Session session = null;

        //login方法写道execute方法中  否则conn值会丢失
        //log方法:验证是否能够远程登录linux主机
        boolean flg = false;
        try {
            putEntity.conn = new Connection(ip);  //创建conn
            // 连接
            putEntity.conn.connect();
            // 认证
            flg = putEntity.conn.authenticateWithPassword(userName, userPwd);  //用户密码进行验证
        } catch (IOException e) {
            throw new Exception("远程连接服务器失败", e);
        }

        //验证成功 flg=true
        try {
            if (flg) {
                // 打开一个会话
                session = putEntity.conn.openSession();   //根据conn得到session值  ***之前login方法写道execute方法外部 报空指针错误   ****原因:程序进入execute时conn已经丢失了 所以session为空 执行失败
                // 执行命令
                session.execCommand(cmd);  //执行cmd命令
                result = processStdout(session.getStdout(), putEntity.DEFAULTCHART);   //命令执行完后返回的结果值
                // 如果result为空,说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    result = processStdout(session.getStderr(), putEntity.DEFAULTCHART);
                }
                putEntity.conn.close();
                session.close();
            }
        } catch (IOException e) {
            throw new Exception("命令执行失败", e);
        } finally {
            if (putEntity.conn != null) {
                putEntity.conn.close();
            }
            if (session != null) {
                session.close();
            }
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     * @param in 输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     */
    @Override
    public String processStdout(InputStream in, String charset) throws Exception {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(stdout, charset);
            br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            throw new Exception("不支持的编码字符集异常", e);
        } catch (IOException e) {
            throw new Exception("读取指纹失败", e);
        } finally {
            IOUtils.close(br);
            IOUtils.close(isr);
            IOUtils.close(stdout);
        }
        return buffer.toString();
    }


}

依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>3.3.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-scala_2.11</artifactId>
            <version>1.13.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-table-planner-blink_2.12</artifactId>
            <version>1.13.3</version>
        </dependency>

    </dependencies>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 并发编程模式之ThreadLocal源码和图文解读

    并发编程模式之ThreadLocal源码和图文解读

    这篇文章主要介绍了并发编程模式之ThreadLocal源码和图文解读,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • springboot如何重定向外部网页

    springboot如何重定向外部网页

    这篇文章主要介绍了springboot如何重定向外部网页,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • java调用shell脚本及注意事项说明

    java调用shell脚本及注意事项说明

    这篇文章主要介绍了java调用shell脚本及注意事项说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • Java中使用Filter过滤器的方法

    Java中使用Filter过滤器的方法

    Filter过滤器是javaWeb层面的,它跟Servlet类似,每次前端请求,首先进入的是过滤器,我们必须实现Filter接口,重写三个方法,才能使用Filter过滤器,需要的朋友可以参考下
    2021-06-06
  • java  Swing基础教程之图形化实例代码

    java Swing基础教程之图形化实例代码

    这篇文章主要介绍了java Swing基础教程之图形化实例代码的相关资料,需要的朋友可以参考下
    2017-02-02
  • SpringBoot如何优雅地使用Swagger2

    SpringBoot如何优雅地使用Swagger2

    这篇文章主要介绍了SpringBoot如何优雅地使用Swagger2,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • SpringFactoriesLoader类作用详解

    SpringFactoriesLoader类作用详解

    SpringFactoriesLoader可以加载jar包下META-INF下的spring.factories,把相关接口的实现按照key,value的形式加载到内存,一个接口的多个实现可以按照","进行分割
    2022-10-10
  • java生成压缩文件示例代码

    java生成压缩文件示例代码

    在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载。写了一个压缩文件的工具类。该工具类支持单个文件和文件夹压缩
    2013-11-11
  • java根据负载自动抓取jstack dump详情

    java根据负载自动抓取jstack dump详情

    这篇文章主要介绍了java根据负载自动抓取jstack dump详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • Springboot项目中定时任务的四种实现方式详解

    Springboot项目中定时任务的四种实现方式详解

    Spring的@Scheduled注解是一种非常简单和便捷的实现定时任务的方式,通过在方法上添加@Scheduled注解,我们可以指定方法在特定的时间间隔或固定的时间点执行,本文给大家介绍Springboot项目中定时任务的四种实现方式,感兴趣的的朋友一起看看b
    2024-02-02

最新评论