java SpringBoot中执行python、shell脚本

前言

最近项目上有一个需求需要暴露rest请求,这个rest请求要去执行python或者shell脚本;

1、目录结构

在这里插入图片描述

2、py示例

print 'hello python'

3、shell示例

echo 'hello shell'
mkdir hello

4、rest接口示例

package com.hxs.demo.soon.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;

/**
 * @Date 2022/8/5
 * @Author hxs
 */
@RestController
@RequestMapping(path = "/api/v1/op")
public class OptionController {
    private static final String PYNAME ="hello.py";
    private static final String SHELLNAME ="hello.sh";

    @GetMapping(path = "/python")
    public List<String> python() {
        String path = OptionController.class.getClassLoader().getResource("").getPath();
        Process proc;
        try {
            //执行脚本
            proc = Runtime.getRuntime().exec("python " + path + PYNAME);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return Collections.singletonList("success");
    }

    @GetMapping(path = "/shell")
    public List<String> shell() {
        String path = OptionController.class.getClassLoader().getResource("").getPath();
        try {
            //先授权
            ProcessBuilder pb = new ProcessBuilder("/bin/chmod", "755", path+SHELLNAME);
            Process ps = pb.start();
            ps.waitFor();

            //执行脚本
            Process process = Runtime.getRuntime().exec(path+SHELLNAME);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return Collections.singletonList("success");
    }
}

5、测试

http://localhost:8980/api/v1/op/shell
在这里插入图片描述
新增的目录
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值